System call open C can't print file content if the file is not opened as sudo

Viewed 607

So I create a new file:

 fd = open("tester.txt", O_CREAT | O_RDWR);

then using the system call write I add some info to it. But when I try to read the info from the file, it can't be made. Using the terminal I found out, that the only way to open the file is to use sudo and the content is successfully written. However, my program can't be root. So, how do I open the file, write some content to it and without closing the C program output the file.

2 Answers

You are missing to specify the file mode as third argument to the creating open call; try the following:

fd = open("tester.txt", O_CREAT | O_RDWR, 0644);

Then, the file should be created with mode -rw-r--r--, so your own user can open it for reading and writing. Otherwise, it might end up with some random permission, i.e. ---------, and only root can open this for reading (without chmodding it, at least).

whenever you are using O_CREAT flag in open() system call, you should explicitly provide the permission. man page of open() says

int open(const char *pathname, int flags, mode_t mode);

mode specifies the permissions to use in case a new file is cre‐ated. This argument must be supplied when O_CREAT is specified in flags; if O_CREAT is not specified, then mode is ignored.

So modify above line as

  fd = open("tester.txt", O_CREAT | O_RDWR, 0664 ); 

I hope it will clear your doubts.

Related