我正在缓存文件中的一些信息,我希望能够定期检查文件的内容是否已被修改,以便我可以再次读取文件以获取新内容(如果需要)。
这就是为什么我想知道是否有办法在C ++中获取文件的最后修改时间。
没有特定于语言的方法,但操作系统提供了所需的功能。在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;
...
}
请注意,有some limitations:
...某些文件系统的[时间]分辨率低至一小时......在程序执行期间,系统时钟可能会被其他一些(可能是自动的)进程设置为新值...
自本文发表以来,c ++ 17已经发布,它包含一个基于boost文件系统库的文件系统库:
https://en.cppreference.com/w/cpp/experimental/fs
其中包括获取最后修改时间的方法:
https://en.cppreference.com/w/cpp/filesystem/last_write_time