檔案open、流fopen、fdopen
阿新 • • 發佈:2019-01-30
Open開啟檔案、fopen開啟流、fdopen在一個已經開啟的檔案描述符上開啟一個流
fclose函式關閉檔案時,該函式會將儲存在記憶體中尚未來得及寫回磁碟的檔案內容寫到磁碟上。如果沒有呼叫fclose函式,就必須等待記憶體中緩衝區被填滿,由系統將其內容寫回到磁碟上去。
由於fclose函式在關閉檔案時會將緩衝區中的內容寫到磁碟上,因此flcose函式實際是進行了一個寫檔案操作。在網路環境中,檔案的內容是要通過網路傳輸到目的主機上並且寫入磁碟的。在這個傳輸過程中,如果網路連接出現問題或者傳輸資料出錯,就會導致檔案內容寫入失敗。這時fclose函式就會出錯。
1 /* FILE: p662_open.c 2 * DATE: 20180124 3 * ============== 4 * DESCRIPTION: open fopen fdopen 5 */ 6 7 #include <stdio.h> 8 // #include <unistd.h> // 巨集 STDOUT_FILENO 9 #include <fcntl.h> 10 11 #define BUFFSIZE 128 12 13 int main(void) 14 { 15 FILE *fp; 16 int fd; 17 char buf[BUFFSIZE]; 18 int len; 19 // fopen 開啟檔案流 20 if((fp=fopen("temp.txt", "w")) == NULL) 21 perror("fail to fopen"); 22 fprintf(fp, "hello world\n"); 23 fclose(fp); 24 25 // open 開啟檔案 26 if((fd=open("temp.txt", O_RDWR)) < 0) 27 perror("fail to open"); 28 // fdopen 在已經開啟的檔案描述符上開啟流 29 if((fp=fdopen(fd, "a")) == NULL) 30 perror("fail to fdopen"); 31 fprintf(fp, "hello world again\n"); 32 fclose(fp); 33 34 write(fileno(stdout), "===\n", 5); // STDOUT_FILENO 35 fp = fopen("temp.txt", "r"); 36 // 讀取檔案 並輸出 37 while((len=fread(buf, sizeof(char), BUFFSIZE-1, fp)) > 0) 38 fprintf(stdout, "%s", buf); 39 40 return 0; 41 }