C++如何检查文件的上次修改时间

Mr.*_*cky 11 c++ file-io last-modified

我正在缓存文件中的一些信息,我希望能够定期检查文件的内容是否已被修改,以便我可以再次读取文件以获取新内容(如果需要).

这就是为什么我想知道是否有办法在C++中获取文件的最后修改时间.

Sme*_*eey 23

没有特定于语言的方法,但操作系统提供了所需的功能.在unix系统中,该stat功能是您所需要的._stat在Visual Studio下为Windows提供了等效的功能.

所以这里是适用于两者的代码:

#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;
    ...
}
Run Code Online (Sandbox Code Playgroud)

  • 修改添加windows支持 (2认同)

小智 12

自这篇文章发布以来,c++17 已经发布,它包含一个基于 boost 文件系统库的文件系统库:

https://en.cppreference.com/w/cpp/header/filesystem

其中包括一种获取上次修改时间的方法:

https://en.cppreference.com/w/cpp/filesystem/last_write_time


The*_*ist 6

你可以使用boost last_write_time.Boost是跨平台的.

是教程链接.

Boost的优点是它适用于各种文件名,因此它处理非ASCII文件名.