2010-12-01 63 views
5

我想检查一个文件,看看它是否已被更改,如果是,然后再次加载它..为此,我开始以下代码,这是让我无处...C++文件的时间戳

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

所有的代码都是打印相同的文件..连续不变。

+0

`如果(newdate ==日期){...}否则,如果(newdate!=日期){...}`我认为这是因为有第三种可能性这里;) – ybungalobill 2010-12-01 10:09:46

回答

9

这是因为你在回路外面呼叫stat()

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

+0

:D ROTFL ... 对不起,感谢.. – 2010-12-01 09:53:51

2

那么,你在stat之前的循环。您通过初始stat获得的信息从不更新。将呼叫移至statwhile循环中。

0

如果您在Linux上并专门为该平台编写代码,则可以使用inotify在文件更改时通知您而不是持续轮询它。

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

0

是的,你必须在while循环中移动统计调用。 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; 
    } 
}