在 C 語言開發中,我們經常需要在讀取文件前預先得知文件大小,以便分配合適的緩衝區、執行文件拷貝或動態創建數組。標準庫函數 fseek 和 ftell 組合使用,即可輕鬆實現這一需求。
函數原型:
int fseek(FILE *stream, long int offset, int whence);
SEEK_SET:文件開頭SEEK_CUR:當前位置SEEK_END:文件結尾whence 的偏移量(字節)。簡單說,fseek 將文件指針從指定基準位置移動 offset 字節。
函數原型:
long int ftell(FILE *stream);
邏輯很直觀:先用 fseek(fp, 0, SEEK_END) 將指針移至文件末尾,再用 ftell(fp) 讀取此時的偏移量,即為文件總字節數。
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
FILE *fp = fopen("addoverflowDemo.c", "r");
if (fp == NULL) {
perror("文件打開失敗");
return EXIT_FAILURE;
}
// 移動指針到文件末尾
if (fseek(fp, 0, SEEK_END) != 0) {
perror("fseek 失敗");
fclose(fp);
return EXIT_FAILURE;
}
// 獲取當前位置 = 文件大小
long size = ftell(fp);
if (size == -1L) {
perror("ftell 失敗");
} else {
printf("文件大小:%ld 字節\n", size);
}
fclose(fp);
return EXIT_SUCCESS;
}
文件大小:309 字節
"rb")下結果最精確,文本模式在 Windows 上可能因換行符轉換導致偏差。fseeko/ftello 或 _fseeki64/_ftelli64 避免溢位。fopen、fseek、ftell 的返回值,增強健壯性。fseek + ftell 是 C 語言獲取文件大小的經典組合,代碼簡潔、移植性好,是每位 C 程序員必備的基本功。