C ++如何检查文件的最后修改时间 [英] C++ How to check the last modified time of a file

查看:260
本文介绍了C ++如何检查文件的最后修改时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

这就是为什么我想知道是否存在一种方法来获取C ++中文件的上次修改时间.

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

推荐答案

没有特定于语言的方法来执行此操作,但是OS提供了必需的功能.在UNIX系统中,您需要stat函数.在Visual Studio下为Windows提供了等效的_stat函数.

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

这篇关于C ++如何检查文件的最后修改时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆