C++ 文件的时间戳(c+)+;

C++ 文件的时间戳(c+)+;,c++,timestamp,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.

我想检查一个文件,看看它是否已更改,如果已更改,然后再次加载。。为此,我从下面的代码开始,这对我来说毫无意义

#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;
            }
    }
}
#包括
#包括
#包括
#包括
使用名称空间std;
int main()
{
结构统计;
int ierr=stat(“readme.txt”和&st);
如果(ierr!=0){

cout这是因为您在循环外部调用
stat()


stat()的结果在特定时刻是正确的。您需要调用stat()每次你想检查它时,都要再次检查。

好吧,你在循环之前就要执行
stat
。你通过初始
stat
获得的信息永远不会更新。将对
stat
的调用移动到
while
循环中。

如果你是在Linux上,并且是专门为该平台编写的,你可以使用inotify来通知你当文件发生错误时而不是不断地轮询它


请参阅man inotify以了解如何使用。

是的,您必须在while循环中移动stat调用。 您的while循环应该如下所示

while(1){
    ierr = stat ("/Volumes/Backup/song.rtf", &st);
    int newdate = st.st_mtime;
    usleep(500000);
    if (newdate==date){
        cout << "same file.. no change" << endl;
    }
    else if (newdate!=date){
        cout << "file changed" << endl;
    }
}
while(1){
ierr=stat(“/Volumes/Backup/song.rtf”、&st);
int newdate=st.st\u mtime;
美国LEEP(500000);
如果(newdate==日期){
cout
if(newdate==date){…}else if(newdate!=date){…}
我想这是因为这里有第三种可能性;)