Tempfile
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:
- A
tempfile()
function that returns standardFile
objects - A
NamedTempFile
struct which provides apath()
method an and can be dereferenced into aFile
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:
tempfile()
will (almost) never fail to cleanup temporary files whileNamedTempFile
will if the destructor isn't run for some reason (i.g. the program aborts, theNameTempFile
is leaked, etc.).- 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.