推荐使用C++17的std::filesystem::file_size获取文件大小,简洁跨平台;2. 兼容性方案可用fstream的seekg与tellg;3. 类Unix系统可选用stat函数;4. Windows平台支持GetFileSizeEx处理大文件。

在C++中获取文件大小有多种方式,常用的方法包括使用标准库和系统相关的API。下面介绍几种实用且跨平台或特定平台下常见的实现方法。
1. 使用 std::filesystem(C++17 及以上)
现代C++推荐使用 std::filesystem 库,简洁且跨平台。通过 file_size() 函数可以直接获取文件大小(以字节为单位):
#include <filesystem>
#include <iostream>
<p>namespace fs = std::filesystem;</p><p>int main() {
try {
std::string filename = "example.txt";
std::uintmax_t size = fs::file_size(filename);
std::cout << "文件大小: " << size << " 字节\n";
} catch (const fs::filesystem_error& ex) {
std::cerr << "错误: " << ex.what() << '\n';
}
return 0;
}注意:需要编译器支持 C++17 并链接 filesystem 库(如 g++ 需加 -lstdc++fs 或 -lstdc++,视版本而定)。2. 使用 fstream 结合 seekg 和 tellg
适用于不支持 C++17 的环境,兼容性好。通过将文件指针移动到末尾,再用 tellg() 获取位置来得到文件大小:
立即学习“C++免费学习笔记(深入)”;
#include <iostream>
#include <fstream>
<p>int main() {
std::ifstream file("example.txt", std::ios::binary | std::ios::ate);
if (!file.is_open()) {
std::cerr << "无法打开文件\n";
return -1;
}</p><pre class='brush:php;toolbar:false;'>std::streamsize size = file.tellg();
file.close();
std::cout << "文件大小: " << size << " 字节\n";
return 0;}
关键点:- 打开模式需包含 std::ios::ate,使文件指针初始位于末尾。
- 使用 binary 模式避免文本换行符转换影响大小计算。
3. 使用 POSIX stat 函数(仅限类Unix系统)
在 Linux 或 macOS 下可使用 stat() 系统调用。#include <sys/stat.h>
#include <iostream>
<p>int main() {
struct stat buffer;
if (stat("example.txt", &buffer) == 0) {
std::cout << "文件大小: " << buffer.st_size << " 字节\n";
} else {
std::cerr << "获取文件信息失败\n";
}
return 0;
}适用于需要高性能或底层控制的场景,但不具备跨平台性。4. Windows API 方法(仅限Windows)
在Windows平台上可使用 GetFileSize 或 GetFileSizeEx。#include <windows.h>
#include <iostream>
<p>int main() {
HANDLE hFile = CreateFileA("example.txt", GENERIC_READ, 0, NULL,
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
std::cerr << "无法打开文件\n";
return -1;
}</p><pre class='brush:php;toolbar:false;'>LARGE_INTEGER size;
if (GetFileSizeEx(hFile, &size)) {
std::cout << "文件大小: " << size.QuadPart << " 字节\n";
} else {
std::cerr << "获取大小失败\n";
}
CloseHandle(hFile);
return 0;}适合Windows原生开发,处理大文件更安全(支持64位大小)。
基本上就这些常见方式。优先推荐 std::filesystem::file_size(C++17),否则用 fseek/tellg 组合保证兼容性。根据项目需求选择合适方法即可。











