How to delete all the files in a directory in Rust?
In rust there are many ways to delete all files in a directory, but before trying to delete them you should make sure none of these files is being opened or used by any program because there will be a lock on the file and that will cause a problem executing your application.1) Delete file by delete complete directory and recreate it
Using this way it will delete the folder completely usingfs::remove_dir_all
and then recreate the same folder again using fs::create_dir
#![allow(unused)]
use std::fs;
fn main() {
let path = "tmp/folderWithFiles";
fs::remove_dir_all(path).unwrap();
fs::create_dir(path).unwrap();
}
2) Delete file by delete iterating through them
Using this way it will delete the files one by one by getting all files using functionread_dir()
use std::fs;
use std::io;
use std::path::Path;
fn remove_dir_contents<P: AsRef<Path>>(path: P) -> io::Result<()> {
for entry in fs::read_dir(path)? {
fs::remove_file(entry?.path())?;
}
Ok(())
}
fn main() {
remove_dir_contents("tmp/folderWithFiles").unwrap();
}