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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40504281/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 15:23:21  来源:igfitidea点击:

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

c++file-iolast-modified

提问by Mr. Nicky

I'm caching some information from a file and I want to be able to check periodically if the file's content has been modified so that I can read the file again to get the new content if needed.

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

That's why I'm wondering if there is a way to get a file's last modified time in C++.

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

回答by Smeeheey

There is no language-specific way to do this, however the OS provides the required functionality. In a unix system, the statfunction is what you need. There is an equivalent _statfunction provided for windows under Visual Studio.

没有特定语言的方法可以做到这一点,但是操作系统提供了所需的功能。在 unix 系统中,stat函数就是你所需要的。_stat在 Visual Studio 下为 windows 提供了一个等效的功能。

So here is code that would work for both:

所以这里的代码对两者都适用:

#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;
    ...
}

回答by Dylan95

since the time of this post, c++17 has been released, and it includes a filesystem library based on the boost filesystem library:

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

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

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

which includes a way to get the last modification time:

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

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

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

回答by The Quantum Physicist

You can use boost's last_write_timefor that. Boost is cross platform.

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

Here's the tutorial link for that.

是教程链接。

Boost has the advantage that it works for all kinds of file names, so it takes care of non-ASCII file names.

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

回答by pooya13

Please note that there are 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 ...

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