代碼先上:
#include<stdio.h> #include<unistd.h> #include<fcntl.h> #include<sys/types.h> #include<sys/stat.h> #include<stdlib.h> /*自定義錯誤處理函數*/ void my_err(const char * err_string,int line)//錯誤處理函數學習筆記三中有記錄 { fprintf(stderr,"line:%d",line); perror(err_string); exit(1); } int main() { int ret; int access_mode; int fd; if((fd=open("example_64",O_CREAT|O_TRUNC|O_RDWR,S_IRWXU))==-1){ //以讀寫打開example_64文件,如果不存在則創建,如果存在則把內容清空,用戶 my_err("open",__LINE__); //權限可讀可寫可執行,打開失敗則調用錯誤處理函數 } /*設置文件打開方式*/ if((ret=fcntl(fd,F_SETFL,O_APPEND))<0){ my_err("fcntl",__LINE__); } /*獲取文件打開方式*/ if(ret=fcntl(fd,FGETFL,0))<0){ my_err("fcntl",__LINE__); } access_mode=ret&O_ACCMODE; if(access_mode==O_RDONLY){ printf("example_64 access mode: read only"); }else if(access_mode == O_WRONLY){ printf("example_64 access mode: write only"); } if(ret&O_APPEND){ printf(",append"); } if(ret & O_SYNC){ printf(",sync"); } printf("\n"); return 0; }ret=fcntl(fd,F_SETFL,O_APPEND) shell man fcntl下查看函數: 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 change only the O_APPEND, O_ASYNC O_DIRECT, O_NOATIME, and O_NONBLOCK flags. It is not possible to change the O_DSYNC and O_SYNC flags; see BUGS, below.
設置被參數arg指定的文件狀態標志值。在liux下這個命令只可以改變O_APPEND, O_ASYNC O_DIRECT, O_NOATIME, O_NONBLOCK、標志,其它的標志不可以改變
ret=fcntl(fd,FGETFL,0) Get the file access mode and the file status flags; arg is gnored.返回值當輸入參數為F_GETFL Value of file status flags.返回值為文件狀態標志。 access_mode=ret&O_ACCMODE;O_ACCMODE的值為三,這句是為了獲得ret後兩位的值,然後判斷文件的打開方式