Skip to content

Instantly share code, notes, and snippets.

@rcook
Created April 18, 2024 20:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcook/def9f889ea0e923cd5d5a7a7b4bc78c1 to your computer and use it in GitHub Desktop.
Save rcook/def9f889ea0e923cd5d5a7a7b4bc78c1 to your computer and use it in GitHub Desktop.
Show creation and modification times for files in a directory
use anyhow::Result;
use chrono::{DateTime, Local};
use std::collections::VecDeque;
use std::fs::{metadata, read_dir};
use std::iter::once;
use std::path::{Path, PathBuf};
use std::time::SystemTime;
fn main() -> Result<()> {
let mut queue =
once(PathBuf::from("/path/to/directory")).collect::<VecDeque<_>>();
while let Some(d) = queue.pop_front() {
for entry in read_dir(d)? {
let entry = entry?;
let file_type = entry.file_type()?;
if file_type.is_dir() {
queue.push_back(entry.path());
} else if file_type.is_file() {
process_file(&entry.path())?;
}
}
}
Ok(())
}
fn process_file(path: &Path) -> Result<()> {
macro_rules! into_date_time {
($system_time:expr) => {
<SystemTime as Into<DateTime<Local>>>::into($system_time)
};
}
let meta = metadata(path)?;
println!(
"{:?} {:?} {:?}",
path,
into_date_time!(meta.created()?),
into_date_time!(meta.modified()?),
);
Ok(())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment