【问题标题】:Change file permission through F_SETFL通过 F_SETFL 更改文件权限
【发布时间】:2012-11-14 18:46:22
【问题描述】:

我最近开始学习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

新的只读属性

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

【问题讨论】:

    标签: file unix


    【解决方案1】:

    您应该使用 chmod 或 fchmod 来更改文件的许可。 chmod 与 argu 文件的路径和 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 标志。

    【讨论】:

    • 也就是说不能通过代码来改变访问权限?
    • 'O_NOATIME' 未声明(在此函数中首次使用)。 O_NOATIME 取决于 CFLAGS = -D_GNU_SOURCE
    猜你喜欢
    • 1970-01-01
    • 2012-12-22
    • 1970-01-01
    • 1970-01-01
    • 2011-10-16
    • 2016-02-22
    • 2017-06-15
    • 2012-02-16
    • 2013-06-27
    相关资源
    最近更新 更多