alphazwest
alphazwest

Reputation: 4450

How do I update a file's modification time?

I'm trying to update the file modification metadata of a file. I can access the Metadata:

use std::fs;

fn main() -> std::io::Result<()> {
    let metadata = fs::metadata("foo.txt")?;

    if let Ok(time) = metadata.modified() {
        println!("{:?}", time);
    } else {
        println!("Not supported on this platform");
    }
    Ok(())
}

I don't know how to alter that value though. My instinct was to open existing files in append mode and write an empty string — didn't work.

What would a general approach for this look like?

Upvotes: 5

Views: 3324

Answers (3)

Jonathan Feenstra
Jonathan Feenstra

Reputation: 2779

Update: There is no longer a need for an external crate, it can now be done using the standard library:

use std::fs::File;
use std::time::SystemTime;

fn main() {
    let file = File::create("Foo.txt").unwrap();
    file.set_modified(SystemTime::now()).unwrap();
}

Original answer:

The set_file_mtime function from the filetime crate can update the file modification time metadata:

use filetime::{set_file_mtime, FileTime};

fn main() {
    set_file_mtime("foo.txt", FileTime::now()).unwrap();
}

Upvotes: 5

Rtbo
Rtbo

Reputation: 230

No more need of external crate, there is a new API since Rust 1.75.0:

Upvotes: 3

Cecilio Pardo
Cecilio Pardo

Reputation: 1717

You will need a external crate: filetime

Upvotes: 2

Related Questions