2012-11-27 44 views
0

我最近開始學習unix,並且正在嘗試一些與文件相關的簡單程序。 我正試圖通過代碼使用函數F_SETFL來更改文件的訪問權限。 我創建了只有寫權限的文件,現在我試圖通過代碼更新權限。 但所有的權限都被重置。通過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

新的只讀屬性

有人能告訴我是設置更新標誌的正確方法。我提到了文件,但仍不太清楚。

回答

0

您應該使用chmod或fchmod來更改文件的權限。 chmod與爭論文件的路徑和fchmod與fd。

fcntl的標誌F_SETFL只能設置O_APPEND,O_ASYNC,O_DIRECT,O_NOATIME和O_NONBLOCK標誌。

F_SETFL(long) 將文件狀態標誌設置爲由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標誌。

+0

這意味着更改訪問權限不能通過代碼完成? – Abi

+1

'O_NOATIME'未申報(首次在此功能中使用)。 O_NOATIME取決於CFLAGS = -D_GNU_SOURCE – Codefor