歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux基礎 >> Linux技術 >> linux 學習筆記(三):open、creat、close 函數的使用,文件的創建、打開與關閉

linux 學習筆記(三):open、creat、close 函數的使用,文件的創建、打開與關閉

日期:2017/3/3 12:28:04   编辑:Linux技術
<span >參考書籍:linux c編程實戰  百度雲下載鏈接:http://pan.baidu.com/s/1c2iD3X2 密碼: wshq</span>

自學中,看著這本書的pdf文件編程,由於之前學過c語言,所以c語言部分簡單的復習了一下直接跳到了linux下c語言的編程。
本次主要學習了三個函數open、creat、close。詳細了解函數的使用可以在shell下輸入man 函數名 查看詳細說明。。。。啥是shell 對於我這個小白來說 就是終端下直接輸入命令就好了。。。。

在用 man open 時候發現出現的函數不是我想要的open而是一個openvt的函數,百度結果 原來是有兩個手冊,查看open函數需要輸入 man 2 open;
這個函數的使用需要包含三個頭文件
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
open函數:
1.int open(const char *pathname, int flags);
2.int open(const char *pathname, int flags, mode_t mode);
參數 ×pathname :帶路徑的文件名,例題中的“example_62.c" 應該要打開或者創建的文件名字。
參數 flags:選項比較多,可以通過shell下的man 2 open 查看參數的具體意思
O_CREAT:如果文件不存在則創建文件,如果填本參數,則2函數中第三個參數也要填,第三個參數主要限定用戶對文件的操作權限權限
O_EXCL:這個參數在man 2 open 下原文是 Ensure that this call creates the file: if this flag is specified in conjunction with O_CREAT, and pathname already exists,then open() will
fail 。 In general, the behavior of O_EXCL is undefined if it is used without O_CREAT. 這個參數應該是確保這個文件被創建,如果這個文件存在則調用open函數失敗,並且這個參數必須和 O_CREAT結合使用,但是在2.6及以後的內核版本中如果本參數是關於塊設備路徑文件名可以單獨使用。(前面還能看得懂,關於內核和塊設備啥的沒有一點概念


O_TRUNC:如果這個文件已經存在並且為 可讀可寫/只寫 這個文件內容將被清零
其它的值本例子木有用的到,也懶得去查等用到了再去詳細了解。。。。。。
creat函數:
int creat(const char *pathname, mode_t mode);
在open函數的解釋中 有creat() is equivalent to open() with flags equal to O_CREAT|O_WRONLY|O_TRUNC.應該說的是這個函數的功能等於open()函數的flag參數為 O_CREAT|O_WRONLY|O_TRUNC 時的功能。
close函數:
int close(int fd);
這個函數只有一個參數 這個參數為需要關閉文件的描述符調用成功返回0錯誤的返回-1
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<unistd.h>
#include<errno.h>
int main()
{
   int fd;
   if((fd = open("example_62.c",O_CREAT|O_EXCL,S_IRUSR| S_IWUSR)) == -1)
      {
//      if((fd= creat("example_62.c",S_IRWXU)) == -1)
                perror("open");
//              printf("open%s    with errno:%d\n",strerror(errno),errno);
                exit(1);
       }
        else
           printf("create file success\n");
   close(fd);
   return 0;
}

本例子除了上述三個函數還有一個 perro函數和strerror函數
perror 函數 描述: The perror() function produces a message on standard error describing the last error encountered during a call to a system or library function.百度百科上是這樣解釋的:perror(s) 用來將上一個函數發生錯誤的原因輸出到標准設備(stderr)。參數
s 所指的字符串會先打印出,後面再加上錯誤原因字符串。此錯誤原因依照全局變量errno(這裡的說法不准確,errno是一個宏,該宏返回左值) 的值來決定要輸出的字符串。在庫函數中有個errno變量,每個errno值對應著以字符串表示的錯誤類型。當你調用"某些"函數出錯時,該函數已經重新設置了errno的值。perror函數只是將你輸入的一些信息和現在的errno所對應的錯誤一起輸出。運行上述例子,在要創建的文件已經存在的情況下shell下輸出:open: File exists
strerror 函數則是吧error對應的描述符轉化為對應的字符串 例如error值為17 則 strerror(error)返會17這個描述符對應的字符串 本例子為 file exist
Copyright © Linux教程網 All Rights Reserved