標籤:des io ar 使用 sp 檔案 on bs linux
open函數用於開啟和建立一個檔案。
所需標頭檔:
#include<sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
常用函數原型:
int open(const char *pathname, int flags)或者
int open(const char *pathname, int flags, mode_t mode)
函數參數解釋:
pathname參數是要開啟或者建立的檔案名稱(可以包括絕對/相對路徑)。
flags參數是一系列常數值(宏定義常數,以O_開頭),可以選擇多個常數進行按位或運算子連結起來一起使用。
flags必選項:
O_RDONLY:唯讀開啟
O_WRONLY:唯寫開啟
O_RDWR:讀寫開啟
flags常用可選項:
O_APPEND:追加內容在所開啟的檔案結尾。
O_CREAT:若檔案不存在則建立。如果使用此選項需要提供第三個參數mode.
O_EXCL:如果同時指定 了O_CREAT,並且檔案已存在,則出錯返回。可用來測試一個檔案是否存在。
O_TRUNC:如果檔案已存在,並且以唯寫或可讀可寫方式開啟,則將其長度截斷為0位元組。
O_NONBLOCK:可設定裝置檔案以非阻塞開啟。
mode參數用來設定檔案許可權位(八進位表示):
1-----》執行
2-----》寫
4-----》讀
函數傳回值:
open函數執行成功返回當前未使用的最小檔案描述符(file descriptor),失敗返回-1(並且設定出錯資訊)。
例:
touch file
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
int fd = open("file", O_RDWR | O_CREAT);
printf("fd = %d\n", fd);
return 0;
}
執行結果為fd = 3;
linux的一點一滴---open