
在C++中获取文件大小有多种方式,常用的方法包括使用标准库和系统相关的API。下面介绍几种实用且跨平台或特定平台下常见的实现方法。
通过 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;
}通过将文件指针移动到末尾,再用 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;}
关键点:#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;
}#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 组合保证兼容性。根据项目需求选择合适方法即可。
以上就是c++++怎么获取文件大小_c++获取文件大小的常用方式的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号