Search code examples
rustrust-cargorust-macros

How can I remove files with a specific file extension in Rust


I need to remove all the files with ".html" extension from a specific directory in Rust.

Do you have any ideas of how can I do that?


Solution

  • There are 2 parts to removing a file:

    1. Finding the file
    2. Removing the file

    You can easily find the file in Rust by iterating over every file in a directory and checking the extension, like so:

    use std::fs;
    
    for path in fs::read_dir("/path/to/dir").unwrap() {
        let path = path.unwrap().path();
        let extension = path.extension().unwrap();
    }
    

    Now you can use extension to do whatever you want, for example check if it's html and remove the file, like so:

    use std::ffi::OsStr;
    if extension == OsStr::new("html") {
        fs::remove_file(path).unwrap();
    }
    

    Playground (not to actually run it, but to show the full code)


    Alternatively, you can use a crate like glob to make your life easier. Using glob makes your code this:

    use glob::glob;
    for path in glob("/path/to/dir/*.html").unwrap() {
        match path {
            Ok(path) => {
                println!("Removing file: {:?}", path.display());
                std::fs::remove_file(path);
            },
            Err(e) => println!("{:?}", e);
        }
    }
    

    glob wiki article for if you don't know what a glob is