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++ - boost 构建 : Use a feature or a variable

Python 递归函数奇怪的行为

Oracle - 检索具有时间戳值的日期

sql - 以恒定精度格式化时间戳

python - ElasticSearch 在 python 中请求范围时间戳

c++ - 查找循环双链表长度的算法

C++ traits类检测成员函数: compiler error in MSVC 2015 RC

javascript - 如何从 csv 解析 highcharts 中的日期

php - 如何在CakePHP中更改时间戳的格式?

c++ - 如何删除此代码输出的结尾空格