專案中頻繁需要取得檔案大小,C/C++ 提供多種 API,各有適用場景與平台差異。本文整理 4 種常用方法並給出可直接編譯的代碼。
_stat / stat(跨平台、C 標準庫)
#include
#include
using namespace std;
int main() {
const char* filepath = "..\\test.ncb";
struct _stat info;
_stat(filepath, &info); // Linux 用 stat()
int size = info.st_size;
cout << "Size: " << size << endl;
return 0;
}
_stat,POSIX stat)、不需開啟檔案。_stati64/stat64)。fopen + filelength(C 標準庫 + POSIX/Windows 擴充)
#include
#include // Windows filelength 需此
int main() {
const char* filepath = "..\\test.ncb";
FILE* file = fopen(filepath, "rb");
if (file) {
int size = filelength(fileno(file)); // Linux 用 fseek/ftell 組合
printf("Size: %d\n", size);
fclose(file);
}
return 0;
}
filelength 非標準 C(Windows/MSVC 擴充),Linux 需自行 fseek(fp,0,SEEK_END); size=ftell(fp);。CFile::GetLength(Windows MFC 專案)
#include // MFC 核心
int main() {
const char* filepath = "..\\test.ncb";
CFile cfile;
if (cfile.Open(filepath, CFile::modeRead)) {
int size = cfile.GetLength();
printf("Size: %d\n", size);
cfile.Close();
}
return 0;
}
ULONGLONG)、編碼安全。CreateFile + GetFileSize(Windows 原生、支援 64 位)
#include
#include
int main() {
const char* filepath = "..\\test.ncb";
HANDLE h = CreateFile(filepath, FILE_READ_EA, FILE_SHARE_READ, NULL,
OPEN_EXISTING, 0, NULL);
if (h != INVALID_HANDLE_VALUE) {
DWORD size = GetFileSize(h, NULL); // 僅回傳低 32 位
// 大檔案需用 GetFileSizeEx (Win2000+)
printf("Size: %u\n", size);
CloseHandle(h);
}
return 0;
}
GetFileSizeEx 支援 64 位大小 (Windows 2000+)
LARGE_INTEGER size;
GetFileSizeEx(h, &size); // size.QuadPart 為 64 位檔案大小
printf("Size: %lld\n", size.QuadPart);
| 場景 | 推薦方法 |
|---|---|
| 跨平台 C/C++ 專案 | stat/_stat (含 64 位版) |
| Windows 獨立程式、無 MFC | GetFileSizeEx (Win32 API) |
| MFC 專案 | CFile::GetLength |
已開啟 FILE* 流 | fseek/ftell 或 filelength |