Temporary files and cleanup
Quick answer
Temporary files support short-lived work such as testing or intermediate processing. The tempfile crate supplies ownership-aware temporary files and directories. Use unpredictable names and avoid relying on cleanup after abrupt termination.
Ownership and explicit cleanup
The existing candidate lab uses tempfile 3.19.1, a third-party dependency. tempdir() returns an owning guard; path() borrows the directory path. close() consumes the guard and reports cleanup errors, unlike ordinary drop. Use the existing reviewed candidate manifest; its dependency graph is not yet resolved or tested. The first example models a cleanup guard without OS access.
struct Guard<'a>(&'a mut bool);impl Drop for Guard<'_> { fn drop(&mut self) { *self.0 = true; } }fn main() { let mut cleaned = false; { let _guard = Guard(&mut cleaned); } println!("cleaned: {cleaned}"); }Expected stdout (not executed):
cleaned: trueThis boolean model shows when Drop runs; it is not a filesystem cleanup test.
// In a disposable Cargo package: tempfile = "=3.19.1"fn main() -> std::io::Result<()> { let dir = tempfile::tempdir()?; std::fs::write(dir.path().join("note.txt"), b"ok")?; println!("{}", std::fs::read_to_string(dir.path().join("note.txt"))?); dir.close()?; Ok(())}Manual local Rust/Cargo candidate; not executed. Expected behavior:
ok, then explicit cleanupRequires the specified external crate and a local scratch environment.
Common mistake
Do not construct a predictable name in a shared temporary directory and then overwrite it.
Try it yourself
Explain why keeping the TempDir guard alive matters while using its path.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Temporary files and cleanup — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
You must detect failures deleting a temporary directory. What should you do with its guard?
Temporary files and cleanup — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust struct Guard<'a>(&'a mut bool); impl Drop for Guard<'_> { fn drop(&mut self) { *self.0 = true; } } fn main() { let mut cleaned = false; { let _guard = Guard(&mut cleaned); } println!("cleaned: {cleaned}"); } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Temporary files and cleanup — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust // In a disposable Cargo package: tempfile = "=3.19.1" fn main() -> std::io::Result<()> { let dir = tempfile::tempdir()?; std::fs::write(dir.path().join("note.txt"), b"ok")?; println!("{}", std::fs::read_to_string(dir.path().join("note.txt"))?); dir.close()?; Ok(()) } ``` Which outcome or interpretation best matches this example?