要處理二進位資料,fwrite 與 fread 是最直接的武器。下面這個小程式示範了「寫入浮點陣列、關檔、再以讀取模式開啟並印出」的完整流程。
#include <stdio.h>
int main()
{
FILE* pFile;
float buffer[] = { 2.0, 3.0, 8.0 };
pFile = fopen("myfile.bin", "wb"); // 以二進位寫入模式開檔
fwrite(buffer, 1, sizeof(buffer), pFile); // 把浮點陣列寫入 myfile.bin
fclose(pFile); // 關閉檔案
float read[3];
pFile = fopen("myfile.bin", "rb"); // 重新以二進位讀取模式開檔
fread(read, 1, sizeof(read), pFile); // 自檔案讀出資料
printf("%f\t%f\t%f\n", read[0], read[1], read[2]);
fclose(pFile); // 再次關檔
return 0;
}
四個參數的意義要記牢:fwrite(ptr, size, count, stream) 中,size 是單一元素的大小,count 是元素個數,因此寫整塊 buffer 時常見 fwrite(buffer, sizeof(buffer[0]), 3, pFile) 的寫法,它會回傳實際寫入的元素數,可用來檢查是否成功。
模式字串也別忽略:"wb" 與 "rb" 中的 b 代表 binary,在 Windows 上少了它會造成換行被轉換而弄壞資料;在 Linux 上雖無差異,仍建議養成習慣。另外 fread 與 fwrite 的資料布局完全依賴平台,寫出的檔案跨平台或跨編譯器未必相容,若要長期保存,最好自行定義格式或加上版本與結尾檢查。