Reputation: 315
I need to watch for the modification of a file on a Unix based system, and I do not have access to Boost. I am wondering if the following logic is sound. I figure it's probably inefficient, and I know I am wasting a ton of cycles by not sleeping at all in the while loop, but I don't have any estimate for how long the file will go in between modification, and I need to know relatively quickly:
std::time_t getTimeLastModified(const char* filename){
struct stat fileattrib;
stat(filename, &fileattrib);
return fileattrib.st_mtime;
}
int main(){
std::time_t file1_modified_time = getTimeLastModified(coor_file.c_str());
while(difftime(getTimeLastModified(coor_file.c_str()),file1_modified_time)==0){}
// If program execution gets here, file has been modified
}
Upvotes: 2
Views: 1676
Reputation: 174
The logic for checking the mod time is mostly sound.
You only need to error check the stat return value- in case the file is missing.
struct stat fileattrib;
int status = stat(filename, &fileattrib); // Get file stats
if (status < 0)
return((std::time_t)-1); // File missing?
return(fileattrib.st_mtime);
This will mean that you should error check the getTimeLastModified() return value.
If you happen to get an idea of how often you need to poll the file modification time, you can put a call to usleep(unsinged long usec) inside your while loop. Can you do something like this?
const unsigned long polltime = 5000; // 5ms
usleep(polltime);
The other thing to consider is whether to time out. That is, what do you do if the file never changes-- for say 10 minutes (or 600000000 microseconds).
Upvotes: 3