如何使用C++获取文件大小?

如何使用C++获取文件大小?
最新回答
凉风有信

2024-01-01 17:35:38

在C++中获取文件大小可以通过标准库提供的多种方法实现,以下是两种常用方案的详细说明及代码示例:

方法一:使用 std::ifstream::tellg()

原理:通过将文件指针移动到文件末尾,直接获取当前位置(即文件大小)。步骤

  1. 打开文件流。
  2. 使用 seekg(0, std::ios::end) 将指针移动到文件末尾。
  3. 调用 tellg() 获取指针位置(字节数)。
  4. 关闭文件流。

代码示例

#include <iostream>#include <fstream>int main() { std::ifstream file("example.txt", std::ios::binary); // 二进制模式避免换行符转换 if (!file) { std::cerr << "Failed to open file." << std::endl; return 1; } file.seekg(0, std::ios::end); std::streampos fileSize = file.tellg(); // 返回类型为std::streampos file.close(); std::cout << "File size: " << fileSize << " bytes" << std::endl; return 0;}

注意

  • 使用 std::ios::binary 模式打开文件可避免某些系统(如Windows)的换行符转换问题。
  • std::streampos 是带符号类型,超大文件(>2GB)可能需要处理溢出。
方法二:使用 C++17 的 std::filesystem

原理:直接调用 std::filesystem::file_size() 函数,更简洁且支持错误处理。步骤

  1. 检查文件是否存在。
  2. 调用 file_size() 获取大小。

代码示例

#include <iostream>#include <filesystem>int main() { std::filesystem::path filePath("example.txt"); try { if (!std::filesystem::exists(filePath)) { throw std::runtime_error("File not found."); } auto size = std::filesystem::file_size(filePath); std::cout << "File size: " << size << " bytes" << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0;}

优势

  • 更安全(自动处理错误)。
  • 支持符号链接和目录大小计算(需递归遍历)。
扩展:计算目录总大小

使用 std::filesystem::directory_iterator 遍历目录并累加文件大小:

#include <iostream>#include <filesystem>int main() { std::filesystem::path dirPath("my_directory"); uintmax_t totalSize = 0; try { for (const auto& entry : std::filesystem::directory_iterator(dirPath)) { if (entry.is_regular_file()) { totalSize += std::filesystem::file_size(entry.path()); } } std::cout << "Total directory size: " << totalSize << " bytes" << std::endl; } catch (const std::exception& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0;}总结
  • 单文件大小:优先使用 std::filesystem::file_size()(C++17起)。
  • 兼容旧标准:使用 std::ifstream::tellg(),但需注意二进制模式和错误处理。
  • 目录统计:结合 directory_iterator 和 file_size() 实现递归计算。

根据项目需求和C++标准版本选择合适的方法即可。