Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if an open file has been modified in C

Tags:

c

file

fopen

Is there any way to determine if an open file has been modified under POSIX? More specifically, how could I implement is_modified() below?

FILE *f = fopen("myfile", "r+");

// do various things with f

if (is_modified(f))
    foo(f);

To provide some context, I'm writing a module in C that for every file needs to store its hash in a table. The interface provides wrappers for fopen() and fclose() and the hashing can be done when the file is closed. I found several approaches to do this, but neither is as efficient, clean or error-proof as I would love:

  • Compute the hash of every file opened for writing.
  • fflush(f) and check if timestamp has changed.
  • Provide wrappers around fwrite(), fprintf(), etc.

Any suggestions?

like image 721
nccc Avatar asked Dec 25 '11 04:12

nccc


1 Answers

http://rosettacode.org/wiki/File_modification_time#POSIX_utime.28.29

You can check the newest modification against the last modification with the stat() function.

like image 186
nmjohn Avatar answered Oct 28 '22 05:10

nmjohn