EmptyData EmptyData - 6 months ago 9
Linux Question

How to write in file in append mode using fcntl.h

Below is my code:

#include <iostream>
#include <fcntl.h>
#include <unistd.h>
using namespace std;

int main()
{

int filedesc = open("testfile.txt", O_RDWR | (O_APPEND |O_CREAT) ,S_IRWXO);

if (filedesc < 0) {
cout<<"unable to open file";
return -1;
}

if (write(filedesc, "This will be output to testfile.txt", 36) != -1) {
cout<<"writing";
close( filedesc );
}

return 0;
return 0;

}


If i run same above second time the o/p is "unable to open file".
Am i doing something wrong?

Answer

This is a permission issue

Try changing

S_IRWXO 

to

 S_IRWXU

It will work fine

S_IRWXO

read, write, execute/search by others

Reference http://pubs.opengroup.org/onlinepubs/7908799/xsh/sysstat.h.html