How to check in c , linux if a file has been updated/changed .
I want to check a file for update before opening the file and performing extraction/ i/o operations from it.
You have to use inotify.
stat() is worse than useless for this purpose. If the st_mtime is different from the last time you checked it, then this tells you that the file has changed, and all is well.
But what if the st_mtime is the same? There's no guarantee that this means the file wasn't changed within the granularity of the filesystem timestamp. On ext3, for example, the granularity tends to be in multiple milliseconds. You can't rely on the time difference between your checking either, what matters is how quickly the file may have been changed after the last time your process checked it.
So even if the st_mtime is the same, you can't be sure that the file hasn't changed. Therefore you have to assume that it has, and there's no point in deluding yourself by doing the test.
The same issues applies to st_ino, if you are expecting the file (of that name) to be replaced by a new file in a create-and-replace operation. inode numbers can be re-used, and after a couple of replacements, a file (by name) can be back to its original inode number again.
The same problem applies to file size, or even creating a hash of the file. All that allows you to determine is that the file has changed. None of these methods let you be completely confident that it hasn't changed, even hashing (although that approaches confidence).
Don't waste your time with stat(), it's a fool's errand.
Look at the man page for stat(2)
. Get the st_mtime
member of the struct stat
structure, which will tell you the modification time of the file. If the current mtime is later than a prior mtime, the file has been modified.
An example:
int file_is_modified(const char *path, time_t oldMTime) {
struct stat file_stat;
int err = stat(path, &file_stat);
if (err != 0) {
perror(" [file_is_modified] stat");
exit(errno);
}
return file_stat.st_mtime > oldMTime;
}
Here's an introduction to inotify
, if that's what you're looking for.
The canonical way is to check the mtime of the file via stat(2)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With