1 打開流的函數
FIEL * fopen(const char * restrict pathname,const char* restrict type)
FILE *fdopen(int filedes,const char *type)
注意:函數1:第一個參數打開文件的路徑 第二參數打開的方式
函數2:第一個參數為已經打開的文件描述符
2 打開方式理解
特點:type中開頭為a的一般為“追加寫,也就是說文件的讀寫位置在文件的末尾。
type中開頭為b的一般是按照二進制文件的形式打開,其他則是按照文本形式打開。
3 返回值
成功返回file指針,失敗將錯誤的值放入error中
4 關閉流 fclose(FILE *FP)成功返回0 失敗返回eof
注意:fclose()函數在關閉文件的時候將緩沖區中的內容回寫到磁盤上,實際上就是進行了一個文件的操作。在網絡的環境中,文件的內容是要通過網路傳輸到達目的主機並寫入磁盤。那么如果網絡出了問題 這個時候就會導致寫入失敗。
5 例子1:打開關閉流
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <fcntl.h> 4 int main(void) 5 { 6 FILE *fp; 7 int fd; 8 if( (fp = fopen("test.txt", "w+")) == NULL){ /* 以讀寫方式打開流 */ 9 perror("fail to open"); 10 exit(1); 11 } 12 fprintf(fp, "hello world\n"); /* 向該流輸出一段信息,這段信息會反饋到文件上 */ 13 fclose(fp); /* 關閉流 */ 14 if( (fd = open("test.txt", O_RDWR)) == -1){ /* 以讀寫的方式打開文件 */ 15 perror("fail to open"); 16 exit(1); 17 } 18 if((fp = fdopen(fd, "a")) == NULL){ /* 在打開的文件上打開一個流 */ 19 perror("fail to open stream"); 20 exit(1); 21 } 22 fprintf(fp,"hello world again\n"); 23 fclose(fp); /* 關閉流,文件也被關閉 */ 24 return 0; 25 }
6 截圖
打開test.txt