在 C/C++ 中獲取檔案大小有多種 API 可用,本文比較四種常見方法:_stat、filelength、MFC CFile::GetLength、Win32 API GetFileSize,並給出完整可編譯範例程式。
| 方法 | 適用平台 | 備註 |
|---|---|---|
_stat() | 跨平台 (POSIX/Windows) | 需 <sys/stat.h>,回傳結構含 st_size |
filelength(fileno(fp)) | Windows (CRT) | 需先 fopen,再取檔案代碼 |
CFile::GetLength() | MFC 專案 | 物件導向封裝,需 afx.h |
GetFileSize() | Win32 API | 需 CreateFile 取得 Handle,支援大檔案 (配合 GetFileSizeEx) |
#include
#include
#include
#include
#define _AFXDLL
using namespace std;
void main() {
char* filepath = "..\\test.ncb";
// 方法一:_stat
struct _stat info;
_stat(filepath, &info);
cout << info.st_size << endl;
// 方法二:filelength
FILE* file = fopen(filepath, "rb");
if (file) {
cout << filelength(fileno(file)) << endl;
fclose(file);
}
// 方法三:CFile
CFile cfile;
if (cfile.Open(filepath, CFile::modeRead))
cout << cfile.GetLength() << endl;
// 方法四:Win32 API
HANDLE h = CreateFile(filepath, FILE_READ_EA, FILE_SHARE_READ, 0, OPEN_EXISTING, 0, 0);
if (h != INVALID_HANDLE_VALUE) {
cout << GetFileSize(h, NULL) << endl;
CloseHandle(h);
}
}
32 位元 GetFileSize 限制 4GB,大檔案請改用 GetFileSizeEx(需 Vista+)或 GetFileSize 搭配 lpFileSizeHigh 參數。