C linux checks if the file is updated / modified / modified?

How to check c, linux if the file has been updated / modified.

I want to check the file for updating before opening the file and performing extraction / input / output operations from it.

+6
source share
3 answers

Take a look at the man page for stat(2) . Get the st_mtime member of the struct stat structure that tells you the time the file was modified. If the current mtime is later than the previous mtime, the file has been modified.

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 this is what you are looking for.

+11
source

The canonical way is to check the mtime of a file via stat(2) .

+5
source

You need to use inotify.

stat () is worse than useless for this purpose. If st_mtime is different from the last one when you checked it, it means that the file has changed, and everything is fine.

But what if st_mtime is the same? There is no guarantee that this means that the file has not been altered in the granularity of the time stamp of the file system. For example, on ext3, graininess tends to be a few milliseconds. You cannot count on the time difference between your checks; the important thing is how quickly the file could be changed after the last time your process checked it.

So, even if st_mtime is the same, you cannot be sure that the file has not changed. Therefore, you must assume that it is, and it makes no sense to mislead yourself by performing the test.

The same problems apply to st_ino if you expect a file (of this name) to be replaced with a new file in the create-and-replace operation. the inode numbers can be reused, and after several replacements, the file (by name) can again return to its original inode number.

The same applies to file size, or even to creating a file hash. All that allows you to determine that the file has changed. None of these methods allows you to be completely sure that it has not changed, even hashing (although this approaches confidence).

Do not waste your time on stat (), this is a crazy errand.

+5
source

Source: https://habr.com/ru/post/908964/


All Articles