1. 程式人生 > >C語言fprintf, fwrite, fscanf, fread混用問題

C語言fprintf, fwrite, fscanf, fread混用問題

sca fwrite sci ins scan 格式化 格式 asc 讀取

int main(int argc, const char * argv[]) {

// insert code here...

FILE * fp = fopen("test.txt", "w");

fprintf(fp, " %d %d", 3, 5);

int x = 4;

fwrite(&x, sizeof(int), 1, fp);

// int x = ‘1‘;

// fwrite(&x, sizeof(int), 1, fp);

fclose(fp);

fp = fopen("test.txt", "r");

int des = 0;

int des2 = 0;

fscanf(fp, "%d%d", &des, &des2);

printf("des: %d %d\n", des, des2);

fread(&des, sizeof(int), 1, fp);

printf("des: %d\n", des);

return 0;

}

//fscanf按照%d讀取的時候,會跳過前面的n個空白符(\t, \n, ‘ ‘),遇到非數字字符終止,因此後面如果是fwrite,在fprintf最後一個數字上加一個空格一類的區別開來,讓fscanf讀數字終止。

//fprintf和fwrite可以混用,一個是格式化輸出,一個是按字節ascii輸出

C語言fprintf, fwrite, fscanf, fread混用問題