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

久未见 提交于 2019-12-21 07:55:43

问题


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++.


回答1:


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

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



回答2:


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

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.




回答3:


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

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




回答4:


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 ...



来源:https://stackoverflow.com/questions/40504281/c-how-to-check-the-last-modified-time-of-a-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!