open函數屬於Linux中系統IO,用於“打開”文件,代碼打開一個文件意味着獲得了這個文件的訪問句柄。
int fd = open(參數1,參數2,參數3);
int fd = open(const char *pathname,int flags,mode_t mode);
1.句柄(file descriptor 簡稱fd)
首先每個文件都屬於自己的句柄,例如標准輸入是0,標准輸出是1,標准出錯是2。
每打開一個文件就會返回句柄來操作這個文件,一般是從3開始,然后4,5,6一直下去。
close(fd)之后句柄就返回給系統,例如打開一個文件后fd是3,close之后再打開另外一個文件也還是3,但代表的文件不一樣了。
2.使用open前需要先包含頭文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
3.參數1(pathname)
即將要打開的文件路徑,例如:“a.txt”當前目錄下的a.txt文件
4.參數2(flags)
flags分為兩類:主類,副類
主類:O_RDONLY 以只讀方式打開 / O_WRONLY 以只寫方式打開 /O_RDWR 以可讀可寫方式打開
三這是互斥的
副類:
O_CREAT 如果文件不存在則創建該文件
O_EXCL 如果使用O_CREAT選項且文件存在,則返回錯誤消息
O_NOCTTY 如果文件為終端,那么終端不可以調用open系統調用的那個進程的控制終端
O_TRUNC 如果文件已經存在澤刪除文件中原有數據
O_APPEND 以追加的方式打開
主副可以配合使用,例如:O_RDWR|O_CREAT|O_TRUNC
5.參數3(mode)
mode:如果文件被新建,指定其權限未mode
mode是八進制權限碼,0777表示文件所有者 該文件用戶組 其他用戶都有可讀可寫可執行權限
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main() { int fd; //創建新文件 fd=open("myhello",O_RDWR | O_CREAT,0777); if(fd == -1) { perror("open file"); exit(1); } printf("fd = %d\n",fd); int ret = close(fd); printf("ret = %d\n",ret); if(ret == -1) { perror("close file"); exit(1); } }
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <stdlib.h> #include <stdio.h> int main() { int fd; //創建新文件判斷是否存在 fd=open("myhello",O_RDWR | O_CREAT | O_EXCL,0777); if(fd == -1) { perror("open file"); exit(1); } printf("fd = %d\n",fd); int ret = close(fd); printf("ret = %d\n",ret); if(ret == -1) { perror("close file"); exit(1); } }
原文鏈接:https://blog.csdn.net/weixin_39296438/java/article/details/79422068