I recently started learning unix and I am trying out some simple programs related to files.
I am attempting to change the access permission of a file through code using the function F_SETFL.
I created the file with only write permission and now I am trying to update the permissions through the code.
But all the permissions are getting reset.
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
int main(void) {
int fd =0;
int fileAttrib=0;
/*Create a new file*/
fd = creat("/u01/TempClass/apue/file/tempfile.txt",S_IWUSR);
fileAttrib = fcntl(fd,F_GETFL,0);
if(fileAttrib < 0 ) {
perror("An error has occurred");
}
printf("file Attribute is %d \n",fileAttrib);
switch(fileAttrib) {
case O_RDONLY:
printf("Read only attribute\n");
break;
case O_WRONLY:
printf("Write only attribute\n");
break;
case O_RDWR:
printf("Read Write Attribute\n");
break;
default:
printf("Somethng has gone wrong\n");
}
int accmode = 0;
//accmode = fileAttrib & O_ACCMODE;
accmode = 777;
fileAttrib = fcntl(fd,F_SETFL,accmode);
if(fileAttrib < 0 ) {
perror("An error has occurred while setting the flags");
}
printf("file Attribute is %d \n",fileAttrib);
/*Print the new access permissions*/
switch(fileAttrib) {
case O_RDONLY:
printf("New Read only attribute\n");
break;
case O_WRONLY:
printf("New Write only attribute\n");
break;
case O_RDWR:
printf("New Read Write Attribute\n");
break;
default:
printf("New Somethng has gone wrong\n");
}
exit(0);
}
And this is my output
file Attribute is 1
Write only attribute
file Attribute is 0
New Read only attribute
Could someone tell me the right way to set the updated flags.? I referred the documentation but still not quite clear.
You should use chmod or fchmod to change files’ permitions. chmod with argu file’s path and fchmod with fd.
fcntl ‘s flag F_SETFL can only set O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags.
F_SETFL (long)
Set the file status flags to the value specified by arg. File access mode (O_RDONLY, O_WRONLY, O_RDWR) and
file creation flags (i.e., O_CREAT, O_EXCL, O_NOCTTY, O_TRUNC) in arg are ignored. On Linux this command can
only change the O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME, and O_NONBLOCK flags.