我正在从文件中缓存一些信息,我希望能够定期检查文件的内容是否已被修改,以便我可以再次读取该文件以获取新内容(如果需要)。
这就是为什么我想知道是否有办法在C ++中获取文件的最后修改时间。
答案 0 :(得分:20)
没有特定于语言的方法,但操作系统提供了所需的功能。在unix系统中,stat
功能是您所需要的。在Visual Studio下为Windows提供了等效的_stat
函数。
所以这里的代码适用于两者:
#include <sys/types.h>
#include <sys/stat.h>
#ifndef WIN32
#include <unistd.h>
#endif
#ifdef WIN32
#define stat _stat
#endif
auto filename = "/path/to/file";
struct stat result;
if(stat(filename.c_str(), &result)==0)
{
auto mod_time = result.st_mtime;
...
}
答案 1 :(得分:6)
答案 2 :(得分:1)
还要注意的是,在Windows上复制文件后,副本的last_write_time是原始文件的last_write_time,而不是人们天真的认为的创建副本的时间。
答案 3 :(得分:0)
请注意,有some limitations:
...在某些文件系统上,[时间]分辨率低至一小时...在程序执行过程中,系统时钟可能由其他可能自动的过程设置为新值...
答案 4 :(得分:0)
自发布之时起,c ++ 17已发布,其中包括基于boost文件系统库的文件系统库:
https://en.cppreference.com/w/cpp/experimental/fs
其中包括一种获取上次修改时间的方法:
https://en.cppreference.com/w/cpp/filesystem/last_write_time
答案 5 :(得分:0)
此跨平台库(Mac,Windows,Linux)很容易添加到项目中。它使用#ifdef来编译正确的实现。