C中的檔案處理是使用C語言函數處理建立、開啟、寫入資料、讀取資料、重新命名和刪除等檔案操作的過程。借助這些函數,我們可以執行文件操作來存儲和檢索程序中文件中的數據。
如果我們使用C程式進行輸入和輸出操作,只要程式正在運行,資料就存在,當程式終止時,我們就無法再次使用該資料。需要處理檔案處理才能處理儲存在外部記憶體中的檔案,即儲存和存取電腦外部記憶體的資訊。您可以使用檔案處理永久保留資料。
FILE *in_file = fopen("name_of_file", "r"); // read only
FILE *out_file = fopen("name_of_file", "w"); // write only
// 檔案是否存在
if (in_file == NULL || out_file == NULL)
{
printf("Error! Could not open file\n");
exit(-1); // must include stdlib.h
}
// 寫到檔案 vs 寫到螢幕
fprintf(file, "this is a test %d\n", integer); // write to file
fprintf(stdout, "this is a test %d\n", integer); // write to screen
printf( "this is a test %d\n", integer); // write to screen
// 從檔案/鍵盤讀取。記住符號!
fscanf(file, "%d %d", &int_var_1, &int_var_2);
fscanf(stdin, "%d %d", &int_var_1, &int_var_2);
scanf( "%d %d", &int_var_1, &int_var_2);