C語言 - 第三十七章 | 檔案 I/O - 格式化檔案 I/O
📑 目錄
- 格式化檔案 I/O
格式化檔案 I/O
在C中,可以使用printf()與scanf()針對輸入或輸出進行格式化,在進行檔案I/O時,也可以使用fprintf()與fscanf()來進行格式化。
1 2
| int fprintf(FILE *fp, char *formatstr, arg1, arg2, ...); int fscanf(FILE *fp, char *formatstr, arg1, arg2, ...);
|
下面這個程式使用串流進行格式化檔案I/O,寫入姓名與成績資料至檔案中,然後再將它讀出。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| include <stdio.h>
int main(int argc, char* argv[]) { char ch;
FILE *file = fopen("test.txt", "w"); if(!file) { puts("無法寫入檔案"); return 1; }
fprintf(file, "%s\t%d\r\n", "Justin", 90); fprintf(file, "%s\t%d\r\n", "momor", 80); fprintf(file, "%s\t%d\r\n", "bush", 75);
fclose(file);
file = fopen("test.txt", "r");; if(!file) { puts("無法讀入檔案"); return 1; }
char name[10]; int score;
puts("Name\tScore"); while(fscanf(file, "%s\t%d", name, &score) != EOF) { printf("%s\t%d\n", name, score); }
fclose(file);
return 0; }
|
1 2 3 4 5
| Name Score Justin 90 momor 80 bush 75
|
在程式執行過程開啟的標準輸出stdout、標準輸入stdin、標準錯誤stderr,事實上也是檔案串流的特例,在C中,也常見到以下的方式,以便直接控制這三個標準輸入、輸出、錯誤。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| #include <stdio.h>
int main(int argc, char* argv[]) { char ch;
FILE *file = fopen("test.txt", "w"); if(!file) { fprintf(stderr, "無法寫入檔案\n"); return 1; }
fprintf(file, "%s\t%d\r\n", "Justin", 90); fprintf(file, "%s\t%d\r\n", "momor", 80); fprintf(file, "%s\t%d\r\n", "bush", 75);
fclose(file);
file = fopen("test.txt", "r");; if(!file) { fprintf(stderr, "無法讀入檔案\n"); return 1; }
char name[10]; int score;
puts("Name\tScore"); while(fscanf(file, "%s\t%d", name, &score) != EOF) { fprintf(stdout, "%s\t%d\n", name, score); }
fclose(file);
return 0; }
|

註:以上參考了
格式化檔案 I/O