使用C++17的std::filesystem库可跨平台获取文件属性,通过file_size()获取文件大小,结合last_write_time()与chrono库转换获取文件修改时间。

当我们需要在C++程序里获取一个文件的各种属性,比如它有多大,是什么时候修改的,甚至是创建时间这些信息时,说实话,最直接且现代的答案就是使用C++17引入的
<filesystem>
解决方案: 现代C++(C++17及更高版本)中,
std::filesystem
要获取文件大小,可以使用
std::filesystem::file_size()
#include <iostream>
#include <filesystem>
#include <string>
#include <fstream> // 用于创建示例文件
namespace fs = std::filesystem;
// 获取文件大小
std::uintmax_t getFileSize(const fs::path& p) {
std::error_code ec; // 用于捕获错误
if (fs::exists(p, ec) && !ec && fs::is_regular_file(p, ec) && !ec) {
return fs::file_size(p, ec);
}
// 如果有错误,或者文件不存在/不是常规文件,这里可以打印错误信息
if (ec) {
std::cerr << "获取文件大小失败: " << ec.message() << std::endl;
}
return 0; // 或者抛出异常,或者返回一个特殊值表示错误
}获取文件修改时间则稍微复杂一点,因为它返回的是
std::filesystem::file_time_type
std::chrono
#include <iostream>
#include <filesystem>
#include <string>
#include <chrono> // For time conversions
#include <ctime> // For std::localtime and std::strftime
#include <fstream> // 用于创建示例文件
namespace fs = std::filesystem;
// 获取文件最后修改时间
std::string getLastWriteTime(const fs::path& p) {
std::error_code ec;
if (fs::exists(p, ec) && !ec && fs::is_regular_file(p, ec) && !ec) {
auto ftime = fs::last_write_time(p, ec);
if (ec) {
std::cerr << "获取文件修改时间失败: " << ec.message() << std::endl;
return "N/A";
}
// 将 file_time_type 转换为 system_clock::time_point
// 注意:C++20 提供了更直接的转换,这里用 C++17 的方式
// 实际应用中,file_time_type 的 epoch 可能与 system_clock 不同,
// 这种转换可能不完全准确,但对于大多数场景足够。
// 更准确的做法是使用 C++20 的 std::chrono::current_zone().to_local(ftime)
auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
ftime - fs::file_time_type::clock::now() + std::chrono::system_clock::now()
);
std::time_t c_time = std::chrono::system_clock::to_time_t(sctp);
std::tm* tm_info = std::localtime(&c_time); // 转换为本地时间
char buffer[80];
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d以上就是C++文件属性获取 大小时间等信息读取的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号