e1/
e1.rs

1use std::io::{Read, Seek, SeekFrom, Write};
2use tempfs::{TempFile, TempError};
3
4fn main() -> Result<(), TempError> {
5    // Create a temporary file with a random name in the system's temp directory.
6    #[cfg(feature = "rand_gen")]
7    let mut temp_file = TempFile::new_random::<std::path::PathBuf>(None)?;
8    #[cfg(not(feature = "rand_gen"))]
9    let mut temp_file = TempFile::new("./tmp/hello.txt")?;
10
11    // Write some data to the temporary file.
12    write!(temp_file, "Hello, temporary world!")?;
13
14    // Move back to the start of the file before reading.
15    temp_file.seek(SeekFrom::Start(0))?;
16
17    // Read the file content into a string.
18    let mut content = String::new();
19    temp_file.read_to_string(&mut content)?;
20    println!("Temp file content: {content}");
21
22    // Rename the file (for example, to "output.txt") and persist it,
23    // so that it is not deleted when `temp_file` is dropped.
24    let _permanent_file = temp_file.persist_here("output.txt")?;
25    println!("Temporary file persisted as output.txt");
26
27    Ok(())
28}