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

问题描述 投票:10回答:4

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

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

c++ file-io last-modified
4个回答
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;
    ...
}

6
投票

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

Here的教程链接。

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


0
投票

请注意,有some limitations

...某些文件系统的[时间]分辨率低至一小时......在程序执行期间,系统时钟可能会被其他一些(可能是自动的)进程设置为新值...


0
投票

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

https://en.cppreference.com/w/cpp/experimental/fs

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

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

© www.soinside.com 2019 - 2024. All rights reserved.