tempfile for safe temporary file creation

Marcus Chen Jan 2026
1 tab
use std::io::Write;
use tempfile::NamedTempFile;

fn main() -> std::io::Result<()> {
    let mut tmpfile = NamedTempFile::new()?;
    writeln!(tmpfile, "Hello, temp file!")?;
    println!("Created temp file: {:?}", tmpfile.path());
    Ok(())
} // tmpfile is deleted here
1 file · rust Explain with highlit

The tempfile crate creates temporary files and directories that are automatically cleaned up on drop. I use it in tests, build scripts, and anywhere I need scratch space. tempfile::NamedTempFile gives you a file path, while tempfile::tempfile() creates an anonymous file (no path). For directories, use tempdir(). The cleanup is automatic and panic-safe thanks to RAII. This prevents test pollution and resource leaks. For persistent temp files, call .persist() to move them out of the temp directory. Tempfile is essential for testing code that reads/writes files without littering the filesystem.