When I need to know if a file has changed on me (Linux), I check the file size, device, inode and modified time. I don't usually need to check files for change, so I generally code it up from scratch as required.
For a change I thought I'd wrap it up into a sub and reuse it were needed. Many eyes will hopefully catch anything I've missed. This sub takes a filename, file handle or nothing (in which case the current stored value of stat is used) and returns a unique string representing the current state of the file. The same file (handle) will continue to return the same string until the file changes.
One obvious pitfall I can think of is someone could change the file contents (keeping the same size) then reset the mod time to match the original, but I'm ignoring that. It also occurs to me that this may not be accurate where links are involved.
Note:
I'm not trying to make it work in all environments (I'm pretty sure it won't work as expected in windows).
I'm not trying to positively test that the file contents have changed, only that they 'may' have changed.
I'm also trying to avoid calling in another module to do the job.
# pass in a file name, a file handle or nothing
# returns a unique string that changes when the file changes
sub FileMeta {
if (my $fh = shift) {
my ($dev, $inode, $size, $mtime) = (stat($fh))[0,1,7,9];
return "$size:$dev;$inode:$mtime";
}
else {
my ($dev, $inode, $size, $mtime) = (stat(_))[0,1,7,9];
return "$size:$dev;$inode:$mtime";
}
}
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.