Crate tempfile [] [src]

Temporary files and directories.

  • Use the tempfile() function for temporary files
  • Use the tempdir() function for temporary directories.


This crate provides several approaches to creating temporary files and directories. tempfile() relies on the OS to remove the temporary file once the last handle is closed. TempDir and NamedTempFile both rely on Rust destructors for cleanup.

When choosing between the temporary file variants, prefer tempfile unless you either need to know the file's path or to be able to persist it.

Resource Leaking

tempfile will (almost) never fail to cleanup temporary resources but TempDir and NamedTempFile will if their destructors don't run. This is because tempfile relies on the OS to cleanup the underlying file so the file while TempDir and NamedTempFile rely on their destructors to do so.


In the presence of pathological temporary file cleaner, relying on file paths is unsafe because a temporary file cleaner could delete the temporary file which an attacker could then replace.

tempfile doesn't rely on file paths so this isn't an issue. However, NamedTempFile does rely on file paths.


Create a temporary file and write some data into it:

use tempfile::tempfile;
use std::io::{self, Write};

// Create a file inside of `std::env::temp_dir()`.
let mut file = tempfile()?;

writeln!(file, "Brian was here. Briefly.")?;

Create a temporary directory and add a file to it:

use tempfile::tempdir;
use std::fs::File;
use std::io::{self, Write};

// Create a directory inside of `std::env::temp_dir()`.
let dir = tempdir()?;

let file_path = dir.path().join("my-temporary-note.txt");
let mut file = File::create(file_path)?;
writeln!(file, "Brian was here. Briefly.")?;

// By closing the `TempDir` explicitly, we can check that it has
// been deleted successfully. If we don't close it explicitly,
// the directory will still be deleted when `dir` goes out
// of scope, but we won't know whether deleting the directory
// succeeded.



Create a new temporary file or directory with custom parameters.


A named temporary file.


Error returned when persisting a temporary file fails.


A directory in the filesystem that is automatically deleted when it goes out of scope.


A path to a named temporary file without an open file handle.



Create a new temporary directory.


Create a new temporary directory.


Create a new temporary file.


Create a new temporary file in the specified directory.