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