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

在C++中获取文件大小(即文件的字节大小)有多种方法,适用于不同平台和标准库版本。以下是几种常用且实用的技巧。
示例代码:
#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及以上版本的首选方式。
步骤如下:
立即学习“C++免费学习笔记(深入)”;
示例代码:
#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;"><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 << "文件大小: " << size << " 字节\n"; else std::cerr << "无法打开文件\n"; return 0; }
注意:必须以 "rb" 模式打开,避免文本模式下换行符转换影响位置计算。
示例代码:
#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;"><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 << "文件大小: " << size << " 字节\n"; else std::cerr << "无法打开文件\n"; return 0; }
关键点:
基本上就这些。根据你的编译器支持情况选择合适的方法即可。C++17的 filesystem 最推荐,否则 ifstream 或 C 风格都可稳定工作。
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号