1. 程式人生 > 實用技巧 >C語言檔案的開啟和關閉

C語言檔案的開啟和關閉

 1 //檔案的開啟和關閉
 2 #define _CRT_SECURE_NO_WARNINGS
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 #include<string.h>
 6 int Only_Read_file(FILE* fp)
 7 {
 8     //以只讀方式開啟檔案
 9     fp = fopen("D:/C_sum/test.txt", "r");
10     if (fp == NULL)    //進行判斷,判斷是否成功開啟檔案
11     {
12         perror("fopen error:
"); //perror函式會輸出錯誤描述,會在perror中的字串加上錯誤的報錯來輸出 13 return 0; 14 } 15 printf("test good\n"); 16 fclose(fp); 17 return 1; 18 19 } 20 int Only_Write_file(FILE* fp) 21 { 22 fp = fopen("D:/C_sum/test.txt", "w"); 23 if (fp == NULL) 24 { 25 perror("fopen error:"); 26 return
0; 27 } 28 printf("test Good\n"); 29 fclose(fp); 30 return 1; 31 } 32 int main_file_() 33 { 34 //第一步先申明檔案指標變數 35 FILE* fp = NULL; 36 //第二步開啟檔案 37 38 /*以絕對路徑的方式開啟只寫方式開啟檔案 39 Only_Read_file(fp); 40 */ 41 /*以絕對路徑的方式開啟只寫方式開啟檔案 42 Only_Write_file(fp);
43 */ 44 //最後在採取操作結束後關閉檔案 45 //fclose(fp); 46 return 0; 47 }