通过F_SETFL更改文件权限

时间:2012-11-27 07:25:39

标签: file unix

我最近开始学习unix,我正在尝试一些与文件相关的简单程序。 我试图使用函数F_SETFL通过代码更改文件的访问权限。 我创建的文件只有写权限,现在我试图通过代码更新权限。  但所有权限都被重置。

#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);
}

这是我的输出

文件属性为1

只写属性

文件属性为0

新的只读属性

有人能告诉我设置更新标志的正确方法吗?我提到了文档,但仍然不太清楚。

1 个答案:

答案 0 :(得分:0)

您应该使用chmod或fchmod来更改文件的权限。 chmod与争论文件的路径和fchmod与fd。

fcntl的标志F_SETFL只能设置O_APPEND,O_ASYNC,O_DIRECT,O_NOATIME和O_NONBLOCK标志。

F_SETFL(长)               将文件状态标志设置为arg指定的值。文件访问模式(O_RDONLY,O_WRONLY,O_RDWR)和               arg中的文件创建标志(即O_CREAT,O_EXCL,O_NOCTTY,O_TRUNC)将被忽略。在Linux上,此命令可以               只更改O_APPEND,O_ASYNC,O_DIRECT,O_NOATIME和O_NONBLOCK标志。

相关问题