I do open large files with fopen under c with a kind-of observed folder logic. I'd like to fopen (or at least to fread) the file as soon as it has been copied completely to my observed folder.
How can i detect if another process is writing to a file? Is that possible with standard-c?
Thanks
There's no way to do it with standard C. The best you can do is heuristically notice when file stops changing, e.g. read the last few blocks of the file, sleep n seconds, then read the blocks again and compare against the previous read. You could also try just watching the end of file seek pointer to see when it stops moving, but for large files (size greater than what will fit in a signed long) the POSIX function ftello() is required to do it portably.
It's kind of "rude" but you could keep trying to open it in write mode; as long as it's being written to by some other file, the fopen
will fail. Something like this:
FILE* f;
while( (f = fopen( fname, "w" )) == NULL ) {
sleep( 100 ); // we want to be moderately polite by not continually hitting the file
}
fopen
does not check whether anybody's already writing into a file AFAIK. Can you link up some documentation regarding this - Pavan Manjunath 2012-04-05 20:39