Modified. 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.
Example. 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.
Start In get_modified_secs we panic if we cannot get the metadata for the file. Then we call modified() in a function chain.
Info With 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
Some notes. 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.
Summary. 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).
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Mar 3, 2025 (edit link).