How to create a file inside the `/etc` folder in Linux with C?

Viewed 6267

I'm writing a program in C that will have to check a configuration file every time it starts to set some variables.

At the first start of the program I suppose there won't be any configuration file, so I need to create it (with default settings).

I've been said configurations files of program belongs to the folder /etc, more specifically to a particular folder created on purpose for the program itself (i.e. /etc/myprog). Here comes the first question I should have asked: is it true? Why /etc?

In any case I tried to create that file using this:

open("/etc/myprog/myprog.conf", O_WRONLY | O_CREAT, 0644);

the open returns -1 and sets errno global variable to 2 (i.e. folder does not exist). If I try to create the file straight inside /etc (therefore "/etc/myprog.conf" as first argument of the open) I get instead an errno set to 13 (i.e. permission denied).

Is there a way to grant my program permissions to write in /etc?

EDIT: I see most users are suggesting to use sudo. If possible I would have preferred to avoid this option as this file has to be created just once (at the first start). Maybe I should make 2 different executables? (e.g. myprog_bootstrap and myprog, having to run only the first one with sudo)

2 Answers
Related