intergalactic_baba_yaga intergalactic_baba_yaga - 3 years ago 171
C Question

C: cannot create or append to a file

I am trying to open a file for both read and write operations.
If the file is already there, it should append. (I want to be able to write to it, and maybe read from it later)

However, if the file is there, I cannot append to it (I get a permission denied: cannot create file)

int main()
{
int file;
file = open("redirect.txt", O_RDWR | O_APPEND | O_CREAT, 777);
if(!(file == -1)) //edited per comment
{
close(file);
}
else
perror("File could not be created\n");

return 0;
}


This only opens a new file if it does not exist, but does not append to an existing file if it does exist.

Answer Source

You're forgetting that the mode parameter to open() must be in octal. This will work:

file = open("redirect.txt", O_RDWR | O_APPEND | O_CREAT, 0777);

As zwol also mentioned, it's generally a good idea to create files with 0666 (since they don't need to be executable).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download