C++中获取文件大小推荐使用std::filesystem::file_size(C++17及以上),简洁安全;2. 兼容旧版本可用fseek/ftell(C风格)或ifstream的tellg(C++风格),均需以二进制模式操作确保准确性。

在C++中获取文件大小(即文件的字节大小)有多种方法,适用于不同平台和标准库版本。以下是几种常用且实用的技巧。
使用 std::filesystem(C++17 及以上)
现代C++推荐使用 std::filesystem 库,它提供了简洁直观的接口来获取文件大小。示例代码:
#include <filesystem>
#include <iostream>
<p>int main() {
std::string filename = "example.txt";
try {
std::streamsize 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及以上版本的首选方式。
使用 fseek 和 ftell(C 风格)
在不支持C++17或需要兼容老编译器时,可以使用传统的C语言方法。步骤如下:
立即学习“C++免费学习笔记(深入)”;
- 用 fopen 打开文件(以二进制模式)
- 用 fseek 移动到文件末尾
- 用 ftell 获取当前位置(即文件大小)
- 关闭文件
示例代码:
#include <cstdio>
#include <iostream>
<p>long get_file_size(const char<em> filename) {
FILE</em> file = fopen(filename, "rb");
if (!file) return -1;</p><pre class="brush:php;toolbar:false;">fseek(file, 0, SEEK_END);
long size = ftell(file);
fclose(file);
return size;}
int main() { long size = get_file_size("example.txt"); if (size != -1) std::cout
注意:必须以 "rb" 模式打开,避免文本模式下换行符转换影响位置计算。
使用输入流 ifstream(C++ 风格)
如果你偏好纯C++流操作,可以通过 ifstream 获取文件大小。示例代码:
#include <fstream>
#include <iostream>
<p>std::streamsize get_file_size(const std::string& filename) {
std::ifstream file(filename, std::ios::binary | std::ios::ate | std::ios::in);
if (!file.is_open()) return -1;</p><pre class="brush:php;toolbar:false;">std::streamsize size = file.tellg();
file.close();
return size;}
int main() { auto size = get_file_size("example.txt"); if (size != -1) std::cout
关键点:
- 使用 std::ios::ate 在打开时定位到文件末尾
-
tellg() 返回当前读取位置,即文件总大小
- 以二进制模式打开,确保准确性
基本上就这些。根据你的编译器支持情况选择合适的方法即可。C++17的 filesystem 最推荐,否则 ifstream 或 C 风格都可稳定工作。











