I generally don’t like asking “what’s wrong with my code” questions, but this is my last hope.
I’m doing a project in which I have to write to files, and I’m trying to do it using system calls (Linux). So I’m using unistd.h, which provides the functions: int open( char* filename, int flags, int mode ) and int write( int fd, void* ptr, int numbytes ). I use write all the time with no problem, but that’s normally with the standard out and standard error file descriptors.
So I use this code to open the file:
int flags = O_WRONLY;
if( !exists( "testfile2.txt" ) ) {
flags |= O_CREAT;
}
int mode = S_IROTH | S_IWOTH | S_IXOTH;
int filedesc = open( "testfile2.txt", flags, mode );
And then this line to write to the file:
int written = write(filedesc, "abcdefghijklmnopqrstuvwxyz",
strlen("abcdefghijklmnopqrstuvwxyz" ) );
And finally, I close the file with this:
int closed = close( filedesc );
The problem is that when I try to write to the file when it didn’t already exist, I get a message saying “permission denied”. When I open it in vi and ignore the permissions, the file appears to be empty. However, if the file existed initially, it writes to it and I can read it just fine. Does anyone have any clue what’s going wrong or if I’m missing something?
Thanks in advance.
According to the docs,
O_CREATuses the permission bits only if the file does not exists. You pass a permission mask of 007, denying “owner” and “group” all rights on the file. Use at leastS_IRUSR | S_IWUSRin the mode flags: