Timestamp of file in c++
i want to check a file to see if its been changed and if it is, then load it again.. for this, i started with the following code which is getting me nowhere...
#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){
开发者_C百科 int newdate = st.st_mtime;
usleep(500000);
if (newdate==date){
cout << "same file.. no change" << endl;
}
else if (newdate!=date){
cout << "file changed" << endl;
}
}
}
all the code does is print same file.. no change continuously.
That's because you're calling stat()
outside the loop.
The result from stat() is correct at that particular moment. you need to call stat() again each time you want to check it.
Well, you stat
before the loop. The info you obtain by your initial stat
is never updated. Move the call to stat
into the while
loop.
If you are on Linux and writing specifically for that platform you can use inotify to inform you when a file changes rather than continually polling it.
See man inotify to see how to use.
yes you have to move stat call in while loop. your while loop should look like this
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;
}
}
精彩评论