Securely create and manage temporary files. Temporary files created by this create are automatically deleted.

Links

Example

extern crate tempfile;
use std::fs::File;
use std::io::{Write, Read, Seek, SeekFrom};

fn main() {
    // Write
    let mut tmpfile: File = tempfile::tempfile().unwrap();
    write!(tmpfile, "Hello World!").unwrap();

    // Seek to start
    tmpfile.seek(SeekFrom::Start(0)).unwrap();

    // Read
    let mut buf = String::new();
    tmpfile.read_to_string(&mut buf).unwrap();
    assert_eq!("Hello World!", buf);
}

Variants

This library provides two temporary file variants:

  1. A tempfile() function that returns standard File objects
  2. A NamedTempFile struct which provides a path() method an and can be dereferenced into a File object.

When choosing between the variants, prefer tempfile() unless you either need to know the file's path or need to be able to be able to persist it because:

  1. tempfile() will (almost) never fail to cleanup temporary files while NamedTempFile will if the destructor isn't run for some reason (i.g. the program aborts, the NameTempFile is leaked, etc.).
  2. In the presence of pathological temporary file cleaner, relying on file paths in shared temporary directories is unsafe. The temporary file could be deleted by the temporary file cleaner and then replaced by an attacker with an attacker controlled file.