Sometimes it is helpful to compute a timestamp of when a file was modified. In Rust programs this could be used to determine if a file needs to be parsed again.
With fs metadata, we can access information from the filesystem. And we can access the modified time. In Rust, this is a SystemTime
, which we can convert to seconds with duration_since
.
Here we introduce the get_modified_secs
function. This receives a path to a file, and it returns a usize
that indicates the seconds since it was modified on the disk.
get_modified_secs
we panic if we cannot get the metadata for the file. Then we call modified()
in a function chain.duration_since
, we compute the number of seconds since the start of the UNIX time. Then we call as_secs()
to get a u64
number.use std::fs; pub fn get_modified_secs(file: &str) -> usize { // Get modification timestamp from file. let meta = fs::metadata(file).expect("Need metadata"); let secs = meta .modified() .expect("Need modified date") .duration_since(std::time::UNIX_EPOCH) .expect("Need duration") .as_secs(); secs.try_into().unwrap() } fn main() { let modified = get_modified_secs("programs/example.txt"); println!("MODIFIED TIMESTAMP: {}", modified); }MODIFIED TIMESTAMP: 1692807807
In Rust we have to specify some of our logic carefully—we must compute a duration to get a figure in seconds. The result is an accurate timestamp for the modified time for the file.
By computing a modified timestamp, we can more effectively determine the freshness of files on disk. And we can then update other files only as needed (as an optimization).