#include <stdio.h>
long getFileSize(const char *filename) {
FILE *fp = fopen(filename, "rb"); // 二進位模式避免換行轉換影響位置
if (!fp) return -1;
fseek(fp, 0, SEEK_END);
long size = ftell(fp);
fclose(fp);
return size;
}
int fseek(FILE *stream, long offset, int whence);
// whence: SEEK_SET(0) 開頭, SEEK_CUR(1) 當前, SEEK_END(2) 結尾
// 成功回傳 0,失敗非 0
long ftell(FILE *stream);
// 回傳當前位置相對檔案開頭的位移(位元組數),失敗回傳 -1L
fseek(fp, 0, SEEK_END) 將檔案指標移至檔案結尾。ftell(fp) 回傳該位置的位移,即檔案總位元組數。fseek(fp, 0, SEEK_SET) 歸零。\r\n 轉為 \n,導致 ftell 回傳值不等於實際磁碟位元組數。必須用 "rb" 開啟。fseeko/ftello (POSIX, off_t 64 位) 或 Windows _fseeki64/_ftelli64。fseek 第三參數為 int,offset 為 long,32 位系統受限 2GB。// stat 系統呼叫(更標準、支援 64 位、可取得 inode、權限等)
#include <sys/stat.h>
long getFileSizeStat(const char *path) {
struct stat st;
return (stat(path, &st) == 0) ? st.st_size : -1;
}
FILE *pFile = fopen("test.txt", "rb");
if (pFile == NULL) { perror("fopen"); return 1; }
fseek(pFile, 0, SEEK_END);
long size = ftell(pFile);
fclose(pFile);
printf("Size: %ld bytes\n", size);
fseek + ftell 是 C 標準庫獲取檔案大小的經典組合,理解其二進位模式要求與大檔案限制,是檔案操作的基本功。