2012-11-27 4 views
0

최근 유닉스 학습을 시작했으며 파일과 관련된 간단한 프로그램을 시험해보고 있습니다. 함수 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를 사용해야합니다. argm 파일의 경로가있는 chmod와 fd가있는 fchmod.

fcntl의 플래그 F_SETFL은 O_APPEND, O_ASYNC, O_DIRECT, O_NOATIME 및 O_NONBLOCK 플래그 만 설정할 수 있습니다.

F_SETFL (long) 파일 상태 플래그를 arg로 지정된 값으로 설정하십시오. arg에서 파일 액세스 모드 (O_RDONLY, O_WRONLY, O_RDWR) 및 파일 생성 플래그 (즉, 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