I'm trying to write a string to file, and set the file's permissions to 777. The resulting file is blank and has permissions of 775. The mode mask seems to be correct, and when I check with access(), it returns 0. I can chmod the file to 777 (without using sudo). What's going on?
Running ubuntu 14.10. Hard drive is ext3/4.
if (argc == 1) {
int fd = open ("sampleFile", O_CREAT , S_IRWXU | S_IRWXG | S_IRWXO);
int writ = 0xDEADBEEF;
if (fd != -1) {
char str [] = "My permission should be set to 777.";
writ = write (fd, &str, (int)strlen (str));
//writ = access ("sampleFile", W_OK);
close (fd);
printf ("(%o) %s\n", writ, str);
return 0;
}
else {
printf ("Couldn't make sampleFile in pwd.\n");
return 1;
}
}
You have two problems:
The second argument to write()
"must include one of the following access modes: O_RDONLY
, O_WRONLY
, or O_RDWR
". Change O_CREAT
to O_CREAT | O_WRONLY
to allow writing to the file.
The mode of the created file is modified by your umask
. Your umask
is probably 002
. (A umask
of 002
prevents you from accidentally creating world-writable files.) You can use fchmod
to change the permissions after creating it.:fchmod(fd, S_IRWXU | S_IRWXG | S_IRWXO)