在 C 語言中,可以使用 printf() 與 scanf() 針對輸入或輸出進行格式化,在進行檔案 I/O時,也可以使用 fprintf()
與 fscanf()
來進行格式化:
int fprintf(FILE *fp, char *formatstr, arg1, arg2, ...);
int fscanf(FILE *fp, char *formatstr, arg1, arg2, ...);
下面這個程式使用串流進行格式化檔案 I/O,寫入姓名與成績資料至檔案中,然後再將它讀出:
#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;
}
執行結果會在純文字檔案中儲存以下的內容,並在螢幕上顯示之:
Name Score
Justin 90
momor 80
bush 75
在程式執行過程開啟的標準輸出 stdout
、標準輸入 stdin
、標準錯誤 stderr
,事實上也是檔案串流的特例,在 C 程式中,也常見到以下的方式,以便直接控制這三個標準輸入、輸出、錯誤:
#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;
}
程式的執行結果與上一個範例是相同的。