C++ 如何查看文件的最后修改时间

C++ How to check the last modified time of a file

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

这就是为什么我想知道是否有一种方法可以在 C++ 中获取文件的最后修改时间。

没有特定于语言的方法来执行此操作,但是 OS 提供了所需的功能。在 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;
    ...
}

您可以为此使用 boost 的 last_write_time。 Boost 是跨平台的。

Here 的教程 link。

Boost 的优势在于它适用于所有类型的文件名,因此它可以处理非 ASCII 文件名。

请注意有some limitations:

... The [time] resolution is as low as one hour on some filesystems... During program execution, the system clock may be set to a new value by some other, possibly automatic, process ...

从这篇post开始,c++17已经发布,它包含了一个基于boost文件系统库的文件系统库:

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

其中包括获取最后修改时间的方法:

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

另请注意,复制文件后(在 Windows),副本的 last_write_time 是原始文件的 last_write_time 而不是创建副本的时间,因为天真地认为。

这个 cross-platform 库(Mac、Windows、Linux)很容易添加到项目中。它使用#ifdef 来编译正确的实现。

https://github.com/jameswynn/simplefilewatcher