These two code snippets produce files with different file-permissions. Example 1 creates the expected default file-permissions but Example 2 does not. What’s the explanation for this?
OS: Mac OS X version: 10.6.4
Xcode version: 3.2.2, 64 bit
// Example 1
FILE *fh1 = fopen("Test1.txt", "w+x");
if (fh1) {
fwrite("TEST1", 1, 5, fh1);
fclose(fh1);
}
Creates:
-rw-r–r– 1 me staff 5 29 Jul 00:41 Test1.txt
// Example 2
int fh2 = open("Test2.txt", O_EXCL | O_CREAT | O_WRONLY);
if (fh2 >= 0) {
write(fh2, "TEST2", 5);
close(fh2);
}
Creates:
———- 1 me staff 5 29 Jul 00:41 Test2.txt
When you use
O_CREATyou need to add a third argument toopen, the mode. For instance:This would be equivalent to 0666. Be aware that this mode is then masked by the process’s umask, meaning the permissions you specify will usually be reduced a bit. A typical umask is 0022, which would result in a mode of 0666 & ~0222 = 0644, i.e.
-rw-r--r--.From man open: