[][src]Crate tempfile

Temporary files and directories.

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

Design

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, while TempDir and NamedTempFile rely on their destructors to do so.

Security

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.

Examples

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.
drop(file);
dir.close()?;

Structs

Builder

Create a new temporary file or directory with custom parameters.

NamedTempFile

A named temporary file.

PathPersistError

Error returned when persisting a temporary file path fails.

PersistError

Error returned when persisting a temporary file fails.

SpooledTempFile

An object that behaves like a regular temporary file, but keeps data in memory until it reaches a configured size, at which point the data is written to a temporary file on disk, and further operations use the file on disk.

TempDir

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

TempPath

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

Functions

spooled_tempfile

Create a new spooled temporary file.

tempdir

Create a new temporary directory.

tempdir_in

Create a new temporary directory.

tempfile

Create a new temporary file.

tempfile_in

Create a new temporary file in the specified directory.