使用 std::Filesystem::file_size 是c++17 及以上推荐的跨平台方法,代码简洁且支持异常处理;若不支持 C ++17,linux/macOS 可选用 POSIX stat 函数,windows 平台则可用 GetFileSize 或 GetFileSizeEx API 获取文件大小。

在 C ++ 中获取一个文件的总大小有多种方法,常用的包括使用标准库中的std::filesystem(C++17 及以上)、POSIX 函数stat,以及windows API。下面介绍几种实用且跨平台或平台特定的方法。
方法一:使用 std::filesystem(推荐,C++17)
如果你的编译器支持 C++17,这是最简洁、跨平台的方式。
示例代码:
#include <filesystem> #include <iostream> int main() { std::string filename = "example.txt"; try { std::uintmax_t size = std::filesystem::file_size(filename); std::cout << " 文件大小: " << size << " 字节n"; } catch (const std::filesystem::filesystem_error& ex) {std::cerr << " 错误: " << ex.what() << 'n'; } return 0; }
编译时需启用 C++17:使用 -std=c++17(GCC/Clang)或确保 MSVC 支持。
方法二:使用 POSIX stat 函数(适用于 Linux/macOS)
在类 unix 系统中,可以使用 <sys/stat.h> 中的 stat 函数。
示例代码:
#include <iostream> #include <sys/stat.h> int main() { struct stat buffer; std::string filename = "example.txt"; if (stat(filename.c_str(), &buffer) == 0) {std::cout << " 文件大小: " << buffer.st_size << " 字节 n ";} else {std::cerr << " 无法获取文件信息 n ";} return 0; }
此方法不适用于 Windows 原生环境,除非使用 MinGW 或 WSL。
方法三:使用 Windows API(仅限 Windows)
在 Windows 平台下,可以使用 GetFileSize 或 GetFileSizeEx。
示例代码(使用 GetFileSize):
立即学习“C++ 免费学习笔记(深入)”;
#include <iostream> #include <windows.h> int main() { HANDLE hFile = CreateFile("example.txt", GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) {std::cerr << " 无法打开文件 n "; return 1;} Dword size = GetFileSize(hFile, NULL); if (size != INVALID_FILE_SIZE) {std::cout << " 文件大小: " << size << " 字节 n ";} else {std::cerr << " 获取文件大小失败 n ";} CloseHandle(hFile); return 0; }
注意:大文件(超过 4GB)应使用 GetFileSizeEx 配合 LARGE_INTEGER。
小结
推荐优先使用 std::filesystem::file_size,代码简洁且跨平台。若项目不支持 C++17,则根据 操作系统 选择 stat 或 Windows API。处理异常和文件不存在的情况时,务必加入错误检查。
基本上就这些。选择合适的方法取决于你的编译环境和目标平台。


