Struct NamedTempFile
struct NamedTempFile<F = std::fs::File> { ... }
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:
- A user creates a temporary file with
NamedTempFile::new(). - Time passes.
- The temporary file cleaner deletes (unlinks) the temporary file from the filesystem.
- Some other program creates a new file to replace this deleted temporary file.
- 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, 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.
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
impl NamedTempFile<File>
fn new() -> Result<NamedTempFile>Create a new named temporary file.
See
Builderfor 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:
-
The file has a short lifetime and your temporary file cleaner is sane (doesn't delete recently accessed files).
-
You trust every user on your system (i.e. you are the only user).
-
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:
-
You'll fix it later. No you won't.
-
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,
Erris 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.")?; # Ok::<(), std::io::Error>(())-
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.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.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.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.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.
impl NamedTempFile<File>
fn reopen(self: &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
NamedTempFilewhile holding on toFiles returned by this function; theFiles will remain usable. However, they may not be nameable.Errors
If the file cannot be reopened,
Erris 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()?; # Ok::<(), std::io::Error>(())
impl<F> NamedTempFile<F>
fn path(self: &Self) -> &PathGet 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()); # Ok::<(), std::io::Error>(())fn close(self: 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,
Erris 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()?; # Ok::<(), std::io::Error>(())fn persist<P: AsRef<Path>>(self: 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
selfin the resultingPersistError.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
persistreturns.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,
Erris 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.")?; # Ok::<(), std::io::Error>(())fn persist_noclobber<P: AsRef<Path>>(self: 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
selfin the resulting PersistError.Note: Temporary files cannot be persisted across filesystems.
Atomicity: This method is not guaranteed to be atomic on all platforms, although it will generally be atomic on Windows and modern Linux filesystems. While it will never overwrite a file at the target path, it may leave the original link to the temporary file behind leaving you with two hard links in your filesystem pointing at the same underlying file. This can happen if either (a) we lack permission to "unlink" the original filename; (b) this program crashes while persisting the temporary file; or (c) the filesystem is removed, unmounted, etc. while we're performing this operation.
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,
Erris 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.")?; # Ok::<(), std::io::Error>(())fn keep(self: 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()?; # Ok::<(), std::io::Error>(())fn disable_cleanup(self: &mut Self, disable_cleanup: bool)Disable cleanup of the temporary file. If
disable_cleanupistrue, the temporary file will not be deleted when thisTempPathis dropped. This method is equivalent to callingBuilder::disable_cleanupwhen creating the originalNamedTempFile, which see for relevant warnings.NOTE: this method is primarily useful for testing/debugging. If you want to simply turn a temporary file into a non-temporary file, prefer
NamedTempFile::keep.fn as_file(self: &Self) -> &FGet a reference to the underlying file.
fn as_file_mut(self: &mut Self) -> &mut FGet a mutable reference to the underlying file.
fn into_file(self: Self) -> FTurn this named temporary file into an "unnamed" temporary file as if you had constructed it with [
tempfile()].The underlying file will be removed from the filesystem but the returned
Filecan still be read/written.fn into_temp_path(self: Self) -> TempPathCloses the file, leaving only the temporary file path.
This is useful when another process must be able to open the temporary file.
fn into_parts(self: Self) -> (F, TempPath)Converts the named temporary file into its constituent parts.
Note: When the path is dropped, the underlying file will be removed from the filesystem but the returned
Filecan still be read/written.fn from_parts(file: F, path: TempPath) -> SelfCreates a
NamedTempFilefrom its constituent parts.This can be used with
NamedTempFile::into_partsto reconstruct theNamedTempFile.
impl<F> AsRef for NamedTempFile<F>
fn as_ref(self: &Self) -> &Path
impl<F> Debug for NamedTempFile<F>
fn fmt(self: &Self, f: &mut Formatter<'_>) -> Result
impl<F> Freeze for NamedTempFile<F>
impl<F> From for NamedTempFile<F>
fn from(error: PersistError<F>) -> NamedTempFile<F>
impl<F> RefUnwindSafe for NamedTempFile<F>
impl<F> Send for NamedTempFile<F>
impl<F> Sync for NamedTempFile<F>
impl<F> Unpin for NamedTempFile<F>
impl<F> UnsafeUnpin for NamedTempFile<F>
impl<F> UnwindSafe for NamedTempFile<F>
impl<F: AsFd> AsFd for NamedTempFile<F>
fn as_fd(self: &Self) -> BorrowedFd<'_>
impl<F: AsRawFd> AsRawFd for NamedTempFile<F>
fn as_raw_fd(self: &Self) -> RawFd
impl<F: Read> Read for NamedTempFile<F>
fn read(self: &mut Self, buf: &mut [u8]) -> Result<usize>fn read_vectored(self: &mut Self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize>fn read_to_end(self: &mut Self, buf: &mut Vec<u8>) -> Result<usize>fn read_to_string(self: &mut Self, buf: &mut String) -> Result<usize>fn read_exact(self: &mut Self, buf: &mut [u8]) -> Result<()>
impl<F: Seek> Seek for NamedTempFile<F>
fn seek(self: &mut Self, pos: SeekFrom) -> Result<u64>
impl<F: Write> Write for NamedTempFile<F>
fn write(self: &mut Self, buf: &[u8]) -> Result<usize>fn flush(self: &mut Self) -> Result<()>fn write_vectored(self: &mut Self, bufs: &[IoSlice<'_>]) -> Result<usize>fn write_all(self: &mut Self, buf: &[u8]) -> Result<()>fn write_fmt(self: &mut Self, fmt: Arguments<'_>) -> Result<()>
impl<T> Any for NamedTempFile<F>
fn type_id(self: &Self) -> TypeId
impl<T> Borrow for NamedTempFile<F>
fn borrow(self: &Self) -> &T
impl<T> BorrowMut for NamedTempFile<F>
fn borrow_mut(self: &mut Self) -> &mut T
impl<T> From for NamedTempFile<F>
fn from(t: T) -> TReturns the argument unchanged.
impl<T, U> Into for NamedTempFile<F>
fn into(self: Self) -> UCalls
U::from(self).That is, this conversion is whatever the implementation of
[From]<T> for Uchooses to do.
impl<T, U> TryFrom for NamedTempFile<F>
fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>
impl<T, U> TryInto for NamedTempFile<F>
fn try_into(self: Self) -> Result<U, <U as TryFrom<T>>::Error>