'How can I delete all the files in a directory but not the directory itself in Rust?

How can you delete all the files in a directory without deleting the directory itself?

I thought this would work but it gives an error:

for entry in std::fs::read_dir("tmp/my_items") {
    std::fs::remove_file(entry);
}
the trait `AsRef<std::path::Path>` is not implemented for `ReadDir`


Solution 1:[1]

read_dir returns an iterator over io::Result<DirEntry> objects. DirEntry is not a path itself (it's got many separate features, and they didn't implement silent coercion to Path possibly to avoid confusion), but it has a .path() method. Something like this (based on the example given for .path()) should work:

for entry in std::fs::read_dir("tmp/my_items")? {
    let entry = entry?;
    std::fs::remove_file(entry.path())?;
}

Solution 2:[2]

As another answer has pointed out, std::fs::read_dir returns ReadDir (inside a Result), which is an iterator over DirEntrys (inside Results).

In a similar style to this answer, you could just remove the directory and all its contents and then recreate the directory in one go with Result::and_then.

use std::fs;

let path = "tmp/my_items";
fs::remove_dir_all(path).and_then(|_| fs::create_dir(path))?;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 John Kugelman
Solution 2 Michael Hall