filetime
filetime copied to clipboard
Windows ctime should be set to `mtime` if `mtime < ctime`
The code passes null pointer for the creation time, so it is not changed. (see documentation of SetFileTime
)
https://github.com/alexcrichton/filetime/blob/1df0704e39ab951b669f4acc4128db0c7c16863e/src/windows.rs#L34-L54
With this, it is possible to change modified
time to a time earlier than the created
time, which does not make sense:
//# filetime = "*"
use std::fs;
use std::io;
use std::path::Path;
use std::time::Duration;
use filetime::FileTime;
fn run() -> io::Result<()> {
let filepath = Path::new("test.abc123");
// create the example file if it does not exist:
fs::write(filepath, "hello world")?;
// query the metadata:
let metadata = fs::metadata(filepath)?;
let ctime = FileTime::from(metadata.created()?);
let mtime = FileTime::from(metadata.modified()?);
let atime = FileTime::from(metadata.accessed()?);
println!("ctime: {}, mtime: {}, atime: {}", ctime, mtime, atime,);
// note: as expected the created time will be the same or
// earlier than the last modification time:
assert_eq!(ctime <= mtime, true);
let new_time = FileTime::from(metadata.modified()? - Duration::from_secs(60 * 60 * 24));
filetime::set_file_times(filepath, new_time, new_time)?;
let metadata = fs::metadata(filepath)?;
let ctime = FileTime::from(metadata.created()?);
let mtime = FileTime::from(metadata.modified()?);
let atime = FileTime::from(metadata.accessed()?);
println!("ctime: {}, mtime: {}, atime: {}", ctime, mtime, atime,);
// note: the modified time is now earlier than the created
// time, which should not be possible:
assert_eq!(mtime < ctime, true);
fs::remove_file(filepath)?;
Ok(())
}
fn main() {
run().expect("failed to execute");
}