c++ - C++文件的时间戳

标签 c++ timestamp

我想检查一个文件,看看它是否被更改,如果是,然后再次加载它。为此,我从以下代码开始,但它让我无处可去......

#include <sys/types.h>
#include <sys/stat.h> 
#include <unistd.h>
#include <iostream>

using namespace std;

int main()
{
    struct stat st;
    int ierr = stat ("readme.txt", &st);
    if (ierr != 0) {
            cout << "error";
    }
    int date = st.st_mtime;
    while(1){
            int newdate = st.st_mtime;
            usleep(500000);
            if (newdate==date){
                    cout << "same file.. no change" << endl;
            }
            else if (newdate!=date){
                    cout << "file changed" << endl;
            }
    }
}

所有代码所做的只是打印相同的文件.. 没有连续变化。

最佳答案

那是因为你在循环外调用了 stat()

stat() 的结果在那个特定时刻是正确的。每次要检查时都需要再次调用 stat()。

关于c++ - C++文件的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4323046/

相关文章:

c++ - 将带有捕获的 lambda 传递给遗留回调

C++ lambda 捕获 - 哪个被捕获?

c++ - 我的函数无法正确编译

git rebase 不改变提交时间戳

c++ - 链接基于 Dcmtk 的 C++ 程序的库?

c++ - 如何循环 vector 大小 C++

time - 如何在 Kotlin 中获取当前时间作为时间戳?

sql - 使用 CURRENT_TIMESTAMP 查询时间戳分区表的效率

java - 仅从时间戳中获取日期

windows - 查找在日期之间创建/访问/修改的文件,批处理脚本