
在C++中获取文件大小有多种方法,常用的方式包括使用标准库和系统API。下面介绍几种实用且跨平台或适用于特定系统的实现方式。
从 C++17 开始,std::filesystem 提供了便捷的接口来操作文件系统,获取文件大小非常简单。
#include <filesystem>
std::filesystem::file_size(path) 直接返回字节数示例代码:
#include <iostream>
#include <filesystem>
int main() {
std::string path = "example.txt";
try {
std::uintmax_t size = std::filesystem::file_size(path);
std::cout << "文件大小: " << size << " 字节\n";
} catch (const std::exception& e) {
std::cerr << "错误: " << e.what() << '\n';
}
return 0;
}
注意:需确保编译器支持 C++17 并启用相应标准(如 g++ -std=c++17)。
立即学习“C++免费学习笔记(深入)”;
对于不支持 C++17 的环境,可以通过文件流定位到末尾,再读取当前位置来获取大小。
tellg() 获取总字节数示例代码:
#include <iostream>
#include <fstream>
long getFileSize(const std::string& path) {
std::ifstream file(path, std::ios::binary | std::ios::ate);
if (!file.is_open()) return -1;
return file.tellg();
}
int main() {
long size = getFileSize("example.txt");
if (size != -1)
std::cout << "文件大小: " << size << " 字节\n";
else
std::cout << "无法打开文件\n";
return 0;
}
这种方法兼容性好,适合老版本C++项目。
在类 Unix 系统中,可使用 stat 系统调用来高效获取文件信息。
<sys/stat.h>
stat() 填充结构体,从中提取 st_size示例代码:
#include <iostream>
#include <sys/stat.h>
long getFileSizePOSIX(const std::string& path) {
struct stat buf;
if (stat(path.c_str(), &buf) != 0)
return -1;
return buf.st_size;
}
该方法性能高,常用于系统级程序,但不适用于 Windows。
在 Windows 平台下,可以使用 GetFileSize 或 GetFileAttributesEx。
示例使用 GetFileSize:
#include <iostream>
#include <windows.h>
long long getFileSizeWin(const std::string& path) {
HANDLE hFile = CreateFileA(path.c_str(), GENERIC_READ, FILE_SHARE_READ,
NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
return -1;
LARGE_INTEGER size;
if (!GetFileSizeEx(hFile, &size)) {
CloseHandle(hFile);
return -1;
}
CloseHandle(hFile);
return size.QuadPart;
}
适用于需要精细控制文件操作的 Windows 应用。
基本上就这些。选择哪种方法取决于你的编译环境和目标平台。推荐优先使用 std::filesystem(如果可用),否则 fallback 到 fstream 方式,既简洁又可移植。
以上就是C++如何获取文件大小_C++ 文件大小获取方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号