1

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?

  • 2
    List files then remove the ones whose extension is "html" ? What specific step is a problem ? SO isn't supposed to write all the code for you and the functions are well documented in https://doc.rust-lang.org/std/path/struct.Path.html – Denys Séguret Nov 16 '21 at 09:29
  • https://stackoverflow.com/questions/26076005/how-can-i-list-files-of-a-directory-in-rust – E_net4 Nov 16 '21 at 09:31

1 Answers1

1

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

MindSwipe
  • 7,193
  • 24
  • 47