需將整個檔案讀入記憶體處理 (如解碼),先獲取大小可精確 malloc,避免浪費或不足。
fopen 開啟檔案 (二進位模式 "rb")。fseek(fp, 0, SEEK_END) 移至檔案尾。ftell(fp) 取得位移 = 檔案大小 (位元組)。fseek(fp, 0, SEEK_SET) 回到檔案頭。malloc(size) 分配精確記憶體。fread(buf, 1, size, fp) 一次讀完。fread 返回值與 malloc 失敗。fclose 關閉檔案。#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *fp = fopen("data.bin", "rb");
if (!fp) { perror("開啟失敗"); return 1; }
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fseek(fp, 0, SEEK_SET);
printf("檔案大小: %ld 位元組\n", size);
unsigned char *buf = malloc(size);
if (!buf) { perror("記憶體不足"); fclose(fp); return 1; }
size_t read = fread(buf, 1, size, fp);
if (read != size) { fprintf(stderr, "讀取不完整\n"); }
// 處理 buf...
free(buf);
fclose(fp);
return 0;
}
ftell 返回 long,大於 2GB 檔案在 32 位系統可能溢位,建議用 fseeko/ftello (POSIX) 或 _fseeki64 (Windows)。"rb"。mmap/MapViewOfFile)。