tempfile

Struct NamedTempFile

Source
pub struct NamedTempFile<F = File> { /* private fields */ }
Expand description

A named temporary file.

The default constructor, NamedTempFile::new(), creates files in the location returned by env::temp_dir(), but NamedTempFile can be configured to manage a temporary file in any location by constructing with NamedTempFile::new_in().

§Security

Most operating systems employ temporary file cleaners to delete old temporary files. Unfortunately these temporary file cleaners don’t always reliably detect whether the temporary file is still being used.

Specifically, the following sequence of events can happen:

  1. A user creates a temporary file with NamedTempFile::new().
  2. Time passes.
  3. The temporary file cleaner deletes (unlinks) the temporary file from the filesystem.
  4. Some other program creates a new file to replace this deleted temporary file.
  5. The user tries to re-open the temporary file (in the same program or in a different program) by path. Unfortunately, they’ll end up opening the file created by the other program, not the original file.

§Operating System Specific Concerns

The behavior of temporary files and temporary file cleaners differ by operating system.

§Windows

On Windows, open files can’t be deleted. This removes most of the concerns around temporary file cleaners.

Furthermore, temporary files are, by default, created in per-user temporary file directories so only an application running as the same user would be able to interfere (which they could do anyways). However, an application running as the same user can still accidentally re-create deleted temporary files if the number of random bytes in the temporary file name is too small.

So, the only real concern on Windows is:

  1. Opening a named temporary file in a world-writable directory.
  2. Using the into_temp_path() and/or into_parts() APIs to close the file handle without deleting the underlying file.
  3. Continuing to use the file by path.

§UNIX

Unlike on Windows, UNIX (and UNIX like) systems allow open files to be “unlinked” (deleted).

§MacOS

Like on Windows, temporary files are created in per-user temporary file directories by default so calling NamedTempFile::new() should be relatively safe.

§Linux

Unfortunately, most Linux distributions don’t create per-user temporary file directories. Worse, systemd’s tmpfiles daemon (a common temporary file cleaner) will happily remove open temporary files if they haven’t been modified within the last 10 days.

§Resource Leaking

If the program exits before the NamedTempFile destructor is run, the temporary file will not be deleted. This can happen if the process exits using std::process::exit(), a segfault occurs, receiving an interrupt signal like SIGINT that is not handled, or by using a statically declared NamedTempFile instance (like with lazy_static).

Use the tempfile() function unless you need a named file path.

Implementations§

Source§

impl NamedTempFile<File>

Source

pub fn new() -> Result<NamedTempFile>

Create a new named temporary file.

See Builder for more configuration.

§Security

This will create a temporary file in the default temporary file directory (platform dependent). This has security implications on many platforms so please read the security section of this type’s documentation.

Reasons to use this method:

  1. The file has a short lifetime and your temporary file cleaner is sane (doesn’t delete recently accessed files).

  2. You trust every user on your system (i.e. you are the only user).

  3. You have disabled your system’s temporary file cleaner or verified that your system doesn’t have a temporary file cleaner.

Reasons not to use this method:

  1. You’ll fix it later. No you won’t.

  2. You don’t care about the security of the temporary file. If none of the “reasons to use this method” apply, referring to a temporary file by name may allow an attacker to create/overwrite your non-temporary files. There are exceptions but if you don’t already know them, don’t use this method.

§Errors

If the file can not be created, Err is returned.

§Examples

Create a named temporary file and write some data to it:

use std::io::Write;
use tempfile::NamedTempFile;

let mut file = NamedTempFile::new()?;

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

pub fn new_in<P: AsRef<Path>>(dir: P) -> Result<NamedTempFile>

Create a new named temporary file in the specified directory.

This is equivalent to:

Builder::new().tempfile_in(dir)

See NamedTempFile::new() for details.

Source

pub fn with_suffix<S: AsRef<OsStr>>(suffix: S) -> Result<NamedTempFile>

Create a new named temporary file with the specified filename suffix.

See NamedTempFile::new() for details.

Source

pub fn with_suffix_in<S: AsRef<OsStr>, P: AsRef<Path>>( suffix: S, dir: P, ) -> Result<NamedTempFile>

Create a new named temporary file with the specified filename suffix, in the specified directory.

This is equivalent to:

Builder::new().suffix(&suffix).tempfile_in(directory)

See NamedTempFile::new() for details.

Source

pub fn with_prefix<S: AsRef<OsStr>>(prefix: S) -> Result<NamedTempFile>

Create a new named temporary file with the specified filename prefix.

See NamedTempFile::new() for details.

Source

pub fn with_prefix_in<S: AsRef<OsStr>, P: AsRef<Path>>( prefix: S, dir: P, ) -> Result<NamedTempFile>

Create a new named temporary file with the specified filename prefix, in the specified directory.

This is equivalent to:

Builder::new().prefix(&prefix).tempfile_in(directory)

See NamedTempFile::new() for details.

Source§

impl<F> NamedTempFile<F>

Source

pub fn path(&self) -> &Path

Get the temporary file’s path.

§Security

Referring to a temporary file’s path may not be secure in all cases. Please read the security section on the top level documentation of this type for details.

§Examples
use tempfile::NamedTempFile;

let file = NamedTempFile::new()?;

println!("{:?}", file.path());
Source

pub fn close(self) -> Result<()>

Close and remove the temporary file.

Use this if you want to detect errors in deleting the file.

§Errors

If the file cannot be deleted, Err is returned.

§Examples
use tempfile::NamedTempFile;

let file = NamedTempFile::new()?;

// By closing the `NamedTempFile` explicitly, we can check that it has
// been deleted successfully. If we don't close it explicitly,
// the file will still be deleted when `file` goes out
// of scope, but we won't know whether deleting the file
// succeeded.
file.close()?;
Source

pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<F, PersistError<F>>

Persist the temporary file at the target path.

If a file exists at the target path, persist will atomically replace it. If this method fails, it will return self in the resulting PersistError.

Note: Temporary files cannot be persisted across filesystems. Also neither the file contents nor the containing directory are synchronized, so the update may not yet have reached the disk when persist returns.

§Security

This method persists the temporary file using its path and may not be secure in all cases. Please read the security section on the top level documentation of this type for details.

§Errors

If the file cannot be moved to the new location, Err is returned.

§Examples
use std::io::Write;
use tempfile::NamedTempFile;

let file = NamedTempFile::new()?;

let mut persisted_file = file.persist("./saved_file.txt")?;
writeln!(persisted_file, "Brian was here. Briefly.")?;
Source

pub fn persist_noclobber<P: AsRef<Path>>( self, new_path: P, ) -> Result<F, PersistError<F>>

Persist the temporary file at the target path if and only if no file exists there.

If a file exists at the target path, fail. If this method fails, it will return self in the resulting PersistError.

Note: Temporary files cannot be persisted across filesystems. Also Note: This method is not atomic. It can leave the original link to the temporary file behind.

§Security

This method persists the temporary file using its path and may not be secure in all cases. Please read the security section on the top level documentation of this type for details.

§Errors

If the file cannot be moved to the new location or a file already exists there, Err is returned.

§Examples
use std::io::Write;
use tempfile::NamedTempFile;

let file = NamedTempFile::new()?;

let mut persisted_file = file.persist_noclobber("./saved_file.txt")?;
writeln!(persisted_file, "Brian was here. Briefly.")?;
Source

pub fn keep(self) -> Result<(F, PathBuf), PersistError<F>>

Keep the temporary file from being deleted. This function will turn the temporary file into a non-temporary file without moving it.

§Errors

On some platforms (e.g., Windows), we need to mark the file as non-temporary. This operation could fail.

§Examples
use std::io::Write;
use tempfile::NamedTempFile;

let mut file = NamedTempFile::new()?;
writeln!(file, "Brian was here. Briefly.")?;

let (file, path) = file.keep()?;
Source

pub fn as_file(&self) -> &F

Get a reference to the underlying file.

Source

pub fn as_file_mut(&mut self) -> &mut F

Get a mutable reference to the underlying file.

Source

pub fn into_file(self) -> F

Convert the temporary file into a std::fs::File.

The inner file will be deleted.

Source

pub fn into_temp_path(self) -> TempPath

Closes the file, leaving only the temporary file path.

This is useful when another process must be able to open the temporary file.

Source

pub fn into_parts(self) -> (F, TempPath)

Converts the named temporary file into its constituent parts.

Note: When the path is dropped, the file is deleted but the file handle is still usable.

Source

pub fn from_parts(file: F, path: TempPath) -> Self

Creates a NamedTempFile from its constituent parts.

This can be used with NamedTempFile::into_parts to reconstruct the NamedTempFile.

Source§

impl NamedTempFile<File>

Source

pub fn reopen(&self) -> Result<File>

Securely reopen the temporary file.

This function is useful when you need multiple independent handles to the same file. It’s perfectly fine to drop the original NamedTempFile while holding on to Files returned by this function; the Files will remain usable. However, they may not be nameable.

§Errors

If the file cannot be reopened, Err is returned.

§Security

Unlike File::open(my_temp_file.path()), NamedTempFile::reopen() guarantees that the re-opened file is the same file, even in the presence of pathological temporary file cleaners.

§Examples
use tempfile::NamedTempFile;

let file = NamedTempFile::new()?;

let another_handle = file.reopen()?;

Trait Implementations§

Source§

impl<F: AsFd> AsFd for NamedTempFile<F>

Source§

fn as_fd(&self) -> BorrowedFd<'_>

Borrows the file descriptor. Read more
Source§

impl<F: AsRawFd> AsRawFd for NamedTempFile<F>

Source§

fn as_raw_fd(&self) -> RawFd

Extracts the raw file descriptor. Read more
Source§

impl<F> AsRef<Path> for NamedTempFile<F>

Source§

fn as_ref(&self) -> &Path

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl<F> Debug for NamedTempFile<F>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<F> From<PersistError<F>> for NamedTempFile<F>

Source§

fn from(error: PersistError<F>) -> NamedTempFile<F>

Converts to this type from the input type.
Source§

impl Read for &NamedTempFile<File>

Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>

Reads all bytes until EOF in this source, placing them into buf. Read more
Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize>

Reads all bytes until EOF in this source, appending them to buf. Read more
Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

impl<F: Read> Read for NamedTempFile<F>

Source§

fn read(&mut self, buf: &mut [u8]) -> Result<usize>

Pull some bytes from this source into the specified buffer, returning how many bytes were read. Read more
Source§

fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>

Like read, except that it reads into a slice of buffers. Read more
Source§

fn read_to_end(&mut self, buf: &mut Vec<u8>) -> Result<usize>

Reads all bytes until EOF in this source, placing them into buf. Read more
Source§

fn read_to_string(&mut self, buf: &mut String) -> Result<usize>

Reads all bytes until EOF in this source, appending them to buf. Read more
Source§

fn read_exact(&mut self, buf: &mut [u8]) -> Result<()>

Reads the exact number of bytes required to fill buf. Read more
Source§

fn is_read_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Reader has an efficient read_vectored implementation. Read more
Source§

fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Pull some bytes from this source into the specified buffer. Read more
Source§

fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>

🔬This is a nightly-only experimental API. (read_buf)
Reads the exact number of bytes required to fill cursor. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adaptor for this instance of Read. Read more
1.0.0 · Source§

fn bytes(self) -> Bytes<Self>
where Self: Sized,

Transforms this Read instance to an Iterator over its bytes. Read more
1.0.0 · Source§

fn chain<R>(self, next: R) -> Chain<Self, R>
where R: Read, Self: Sized,

Creates an adapter which will chain this stream with another. Read more
1.0.0 · Source§

fn take(self, limit: u64) -> Take<Self>
where Self: Sized,

Creates an adapter which will read at most limit bytes from it. Read more
Source§

impl Seek for &NamedTempFile<File>

Source§

fn seek(&mut self, pos: SeekFrom) -> Result<u64>

Seek to an offset, in bytes, in a stream. Read more
1.55.0 · Source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
Source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
1.51.0 · Source§

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.80.0 · Source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

Seeks relative to the current position. Read more
Source§

impl<F: Seek> Seek for NamedTempFile<F>

Source§

fn seek(&mut self, pos: SeekFrom) -> Result<u64>

Seek to an offset, in bytes, in a stream. Read more
1.55.0 · Source§

fn rewind(&mut self) -> Result<(), Error>

Rewind to the beginning of a stream. Read more
Source§

fn stream_len(&mut self) -> Result<u64, Error>

🔬This is a nightly-only experimental API. (seek_stream_len)
Returns the length of this stream (in bytes). Read more
1.51.0 · Source§

fn stream_position(&mut self) -> Result<u64, Error>

Returns the current seek position from the start of the stream. Read more
1.80.0 · Source§

fn seek_relative(&mut self, offset: i64) -> Result<(), Error>

Seeks relative to the current position. Read more
Source§

impl Write for &NamedTempFile<File>

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn write_all(&mut self, buf: &[u8]) -> Result<()>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>

Writes a formatted string into this writer, returning any error encountered. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more
Source§

impl<F: Write> Write for NamedTempFile<F>

Source§

fn write(&mut self, buf: &[u8]) -> Result<usize>

Writes a buffer into this writer, returning how many bytes were written. Read more
Source§

fn flush(&mut self) -> Result<()>

Flushes this output stream, ensuring that all intermediately buffered contents reach their destination. Read more
Source§

fn write_vectored(&mut self, bufs: &[IoSlice<'_>]) -> Result<usize>

Like write, except that it writes from a slice of buffers. Read more
Source§

fn write_all(&mut self, buf: &[u8]) -> Result<()>

Attempts to write an entire buffer into this writer. Read more
Source§

fn write_fmt(&mut self, fmt: Arguments<'_>) -> Result<()>

Writes a formatted string into this writer, returning any error encountered. Read more
Source§

fn is_write_vectored(&self) -> bool

🔬This is a nightly-only experimental API. (can_vector)
Determines if this Writer has an efficient write_vectored implementation. Read more
Source§

fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>

🔬This is a nightly-only experimental API. (write_all_vectored)
Attempts to write multiple buffers into this writer. Read more
1.0.0 · Source§

fn by_ref(&mut self) -> &mut Self
where Self: Sized,

Creates a “by reference” adapter for this instance of Write. Read more

Auto Trait Implementations§

§

impl<F> Freeze for NamedTempFile<F>
where F: Freeze,

§

impl<F> RefUnwindSafe for NamedTempFile<F>
where F: RefUnwindSafe,

§

impl<F> Send for NamedTempFile<F>
where F: Send,

§

impl<F> Sync for NamedTempFile<F>
where F: Sync,

§

impl<F> Unpin for NamedTempFile<F>
where F: Unpin,

§

impl<F> UnwindSafe for NamedTempFile<F>
where F: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.

Layout§

Note: Unable to compute type layout, possibly due to this type having generic parameters. Layout can only be computed for concrete, fully-instantiated types.