linux的一點一滴---open

來源:互聯網
上載者:User

標籤: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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.