2024-01-01 17:35:38
在C++中获取文件大小可以通过标准库提供的多种方法实现,以下是两种常用方案的详细说明及代码示例:
方法一:使用 std::ifstream::tellg()原理:通过将文件指针移动到文件末尾,直接获取当前位置(即文件大小)。步骤:
代码示例:
#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::filesystem::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;}总结根据项目需求和C++标准版本选择合适的方法即可。