在c++++中跨平台获取文件最后修改时间的方法是根据操作系统使用不同的系统调用并封装统一接口。windows下通过getfiletime获取文件时间并转换为本地时间输出;linux下使用stat函数获取st_mtime字段并格式化输出;可通过宏定义区分平台,封装成统一接口getlastwritetime调用对应实现;此外需注意路径有效性、时间精度差异及现代c++或boost库的替代方案。

在C++中获取文件的最后修改时间,其实是一个很常见的需求,比如在做文件同步、缓存管理或者日志处理的时候。但因为不同操作系统对文件属性的支持方式不一样,所以实现跨平台的获取方法需要一些技巧。

下面介绍几种常见平台(Windows 和 Linux)下的实现方式,并给出一个简单的跨平台封装思路。
在 Windows 上,可以使用
GetFileTime
立即学习“C++免费学习笔记(深入)”;

#include <windows.h>
#include <iostream>
void GetLastWriteTimeWin(const std::string& filePath) {
HANDLE hFile = CreateFile(filePath.c_str(), GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE) {
std::cerr << "Failed to open file: " << filePath << std::endl;
return;
}
FILETIME ftWrite;
if (!GetFileTime(hFile, NULL, NULL, &ftWrite)) {
std::cerr << "Failed to get file time" << std::endl;
} else {
SYSTEMTIME stUTC, stLocal;
FileTimeToSystemTime(&ftWrite, &stUTC);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC, &stLocal);
std::cout << "Last modified: "
<< stLocal.wYear << "-" << stLocal.wMonth << "-" << stLocal.wDay << " "
<< stLocal.wHour << ":" << stLocal.wMinute << std::endl;
}
CloseHandle(hFile);
}这段代码会输出本地时间格式的最后修改时间。
Linux 使用
stat
lstat
st_mtime

#include <sys/stat.h>
#include <ctime>
#include <iostream>
void GetLastWriteTimeLinux(const std::string& filePath) {
struct stat fileStat;
if (stat(filePath.c_str(), &fileStat) < 0) {
std::cerr << "Failed to get file stats" << std::endl;
return;
}
// 转换为本地时间并打印
char buffer[80];
struct tm tmbuf;
localtime_r(&fileStat.st_mtime, &tmbuf); // 线程安全版本
strftime(buffer, sizeof(buffer), "%Y-%m-%d %H:%M", &tmbuf);
std::cout << "Last modified: " << buffer << std::endl;
}注意这里用了线程安全的
localtime_r
localtime
为了兼容 Windows 和 Linux,可以用宏定义来区分平台:
_WIN32
__linux__
封装成统一接口后调用对应的函数,例如:
void GetLastWriteTime(const std::string& path) {
#ifdef _WIN32
GetLastWriteTimeWin(path);
#elif __linux__
GetLastWriteTimeLinux(path);
#else
std::cerr << "Unsupported platform" << std::endl;
#endif
}这样就能在不同系统下调用对应的方法了。
stat
<filesystem>
boost::filesystem::last_write_time()
基本上就这些。虽然看起来有点平台差异,但只要封装好判断逻辑,用起来还是很方便的。
以上就是C++如何获取文件最后修改时间 跨平台获取文件属性信息的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号