Skip to content

Latest commit

 

History

History
58 lines (49 loc) · 2.18 KB

modified.zh.md

File metadata and controls

58 lines (49 loc) · 2.18 KB

过去 24 小时内,修改过的文件名

[![std-badge]][std] [![cat-filesystem-badge]][cat-filesystem]

通过调用env::current_dir,获得当前工作目录,然后针对fs::read_dir中的每个条目,提取DirEntry::path,并通过fs::Metadata得到元信息。 这个Metadata::modified返回上次修改后的SystemTime::elapsed时间。Duration::as_secs会将时间转换为秒,并与 24 小时(24 _ 60 _ 60 秒)比较。Metadata::is_file则是筛选出目录。

# #[macro_use]
# extern crate error_chain;
#
use std::{env, fs};

# error_chain! {
#     foreign_links {
#         Io(std::io::Error);
#         SystemTimeError(std::time::SystemTimeError);
#     }
# }
#
fn run() -> Result<()> {
    let current_dir = env::current_dir()?;
    println!(
        "Entries modified in the last 24 hours in {:?}:",
        current_dir
    );

    for entry in fs::read_dir(current_dir)? {
        let entry = entry?;
        let path = entry.path();

        let metadata = fs::metadata(&path)?;
        let last_modified = metadata.modified()?.elapsed()?.as_secs();

        if last_modified < 24 * 3600 && metadata.is_file() {
            println!(
                "Last modified: {:?} seconds, is read only: {:?}, size: {:?} bytes, filename: {:?}",
                last_modified,
                metadata.permissions().readonly(),
                metadata.len(),
                path.file_name().ok_or("No filename")?
            );
        }
    }

    Ok(())
}
#
# quick_main!(run);