In general, once the handle to the file is open, the file is open, and nobody changing the directory structure can change that - the file can be moved, renamed, or put something else in its place - it remains open by construction, as in Linux/Unix there is no real delete for files, but only unlink
, which doesn't necessarily delete the file - it just removes the link from the directory. Result: The file handle will stay valid whatever happens to the file.
However, if the underlying device disappears (e.g. the file is on a USB stick that is removed from the system) then the file won't be accessible any longer.
I have a program that opens a huge binary file (> 4 GB) of some other application at start. Afterwards, it watches the file for changes, by querying
long int pos = fseek(filepointer, 0L, SEEK_END);
quite often (every few milliseconds) and reverts to the previous positions, if the result is different from pos_before
. In this case, fgets
is used to read the new data from the file.
Hence, only the tail of the file is scanned for changes, making the whole process fairly lightweight. However, it is affected by the potential problem that the always opened file pointer may become invalid if the file system is changed (see above).
The code does not need to be portable to any non-Linux/Unix systems.
Question:
- How can I detect if the file pointer is still valid after having opened the file successfully (this event may be weeks ago)? I have seen that one might be able to use
fcntl(fileno(filepointer), F_GETFD)
for testing.
Alternative question:
- Would it be feasible to detect changes in the file size in an alternative way? I could think of using periodically
fseek(filepointer, 0L, SEEK_END);
(might be very slow and cause a lot of I/O), or_filelength(fileno(filepointer));
(unclear if this will cause lots of I/O)stat(filename, &st); st.st_size;
(unclear if this will cause any I/O)