e2/
e2.rs

1use std::io::Write;
2use tempfs::{TempDir, TempError};
3
4fn main() -> Result<(), TempError> {
5    // Create a temporary directory with a random name.
6    let mut temp_dir = TempDir::new_random::<std::path::PathBuf>(None)?;
7
8    // Create a temporary file with a specific name.
9    {
10        let file = temp_dir.create_file("test1.txt")?;
11        write!(file, "Content for test1")?;
12    }
13
14    // Create another temporary file with a random name.
15    {
16        let file = temp_dir.create_random_file()?;
17        write!(file, "Random file content")?;
18    }
19
20    // List all the temporary files managed by the directory.
21    for file_path in temp_dir.list_files() {
22        println!("Managed temp file: {file_path:?}");
23    }
24
25    // If the library was built with regex support, search for files matching a pattern.
26    #[cfg(feature = "regex_support")]
27    {
28        let matching_files = temp_dir.find_files_by_pattern(r"^test\d\.txt$")?;
29        for file in matching_files {
30            if let Some(path) = file.path() {
31                println!("Found file matching regex: {path:?}");
32            }
33        }
34    }
35
36    // When `temp_dir` goes out of scope, the directory and all its managed files are automatically deleted.
37    Ok(())
38}