How detect if file was overwrote?,
In my C/C++ program I need to check if the file from what I read have been overwrote (its ino开发者_高级运维de was changed or some new lines were added). If I'm now wrong fstat
and fstat64
can be usefull only when I use Linux but not for windows. Is there any universal (to work for complex OSes) way to do this? And also can you tell me how do this using fstat64?
You can keep track of when the file was last written to know if it has been modified. The cross platform solution is using boost::filesystem. Windows doesn't have fstat64 AFAIK.
http://www.boost.org/doc/libs/1_44_0/libs/filesystem/v2/doc/index.htm
http://rosettacode.org/wiki/File_modification_time#C.2B.2B
#include <boost/filesystem/operations.hpp>
#include <ctime>
#include <iostream>
int main( int argc , char *argv[ ] ) {
if ( argc != 2 ) {
std::cerr << "Error! Syntax: moditime <filename>!\n" ;
return 1 ;
}
boost::filesystem::path p( argv[ 1 ] ) ;
if ( boost::filesystem::exists( p ) ) {
std::time_t t = boost::filesystem::last_write_time( p ) ;
std::cout << "On " << std::ctime( &t ) << " the file " << argv[ 1 ]
<< " was modified the last time!\n" ;
std::cout << "Setting the modification time to now:\n" ;
std::time_t n = std::time( 0 ) ;
boost::filesystem::last_write_time( p , n ) ;
t = boost::filesystem::last_write_time( p ) ;
std::cout << "Now the modification time is " << std::ctime( &t ) << std::endl ;
return 0 ;
} else {
std::cout << "Could not find file " << argv[ 1 ] << '\n' ;
return 2 ;
}
}
I don't have a code sample for you, but can you check the last modified time of the file, against what it was when you first opened it?
Edit
Found a pretty good snippet that appears to do the trick
http://www.jb.man.ac.uk/~slowe/cpp/lastmod.html
精彩评论