If you don't want to poll the file using stat
, and don't mind being Linux-specific, then you can use the inotify API. Your kernel needs to be 2.6.13 or newer and glibc 2.4 or newer (which they will be if you're targeting anything from the past 2 or 3 years). The API basically gives you a file descriptor that you can poll
or select
, and read
to get information about modified files. If your application is interactive, like an editor, then it will typically have some sort of event loop that calls select
or poll
, and can watch your inotify file descriptor for events.
Using inotify is generally preferable stat
, because you get notifications immediately and you don't waste time and disk I/O polling when the file isn't changing. The downside is that might not work over NFS or other networked file systems, and it's not portable.
This page at IBM Developerworks gives some example C code, and the man page is the definitive reference.