
在C++中获取文件的大小和修改日期,可以通过系统调用或标准库结合平台相关API实现。下面介绍跨平台(主要以Windows和Linux)常用的方法,使用<filesystem>(C++17起推荐)以及传统的stat函数。
<filesystem> 库,简洁且跨平台。示例代码:
#include <iostream>
#include <filesystem>
#include <chrono>
#include <iomanip>
<p>int main() {
std::string filename = "test.txt";</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (std::filesystem::exists(filename)) {
// 获取文件大小(字节)
auto size = std::filesystem::file_size(filename);
std::cout << "文件大小: " << size << " 字节\n";
// 获取最后修改时间
auto time = std::filesystem::last_write_time(filename);
// 转换为本地时间并输出
auto sctp = std::chrono::time_point_cast<std::chrono::system_clock::duration>(
time - std::filesystem::file_time_type::clock::now() + std::chrono::system_clock::now()
);
std::time_t cftime = std::chrono::system_clock::to_time_t(sctp);
std::cout << "修改日期: " << std::put_time(std::localtime(&cftime), "%Y-%m-%d %H:%M:%S") << '\n';
} else {
std::cout << "文件不存在\n";
}
return 0;} 编译时需启用C++17:g++ -std=c++17 file.cpp -o file (Linux)或在Visual Studio中设置语言标准。
<sys/stat.h> 和 <ctime>。示例代码(Linux/Windows通用):
#include <iiostream>
#include <sys/stat.h>
#include <ctime>
<p>int main() {
std::string filename = "test.txt";
struct stat buffer;</p><pre class="brush:php;toolbar:false;"><pre class="brush:php;toolbar:false;">if (stat(filename.c_str(), &buffer) == 0) {
// 文件大小
std::cout << "文件大小: " << buffer.st_size << " 字节\n";
// 修改时间
std::time_t modTime = buffer.st_mtime;
char* timeStr = std::ctime(&modTime);
timeStr[strlen(timeStr)-1] = '\0'; // 去掉换行符
std::cout << "修改日期: " << timeStr << '\n';
} else {
std::cout << "无法获取文件信息\n";
}
return 0;}
注意:stat 在Windows中可用,但路径分隔符需注意。Windows也提供 _stat 变体,如 _stat64 支持大文件。
std::filesystem::file_size() 和 std::filesystem::last_write_time()(C++17)file_time_type 转为 system_clock 才能格式化输出
stat 方法兼容性好,适合嵌入式或老编译器环境基本上就这些。根据项目环境选择合适方式,新项目建议直接用 <filesystem>。不复杂但容易忽略时间转换细节。
立即学习“C++免费学习笔记(深入)”;
以上就是c++++如何获取文件的大小和修改日期_c++ 文件大小与修改日期获取方法的详细内容,更多请关注php中文网其它相关文章!
c++怎么学习?c++怎么入门?c++在哪学?c++怎么学才快?不用担心,这里为大家提供了c++速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号