Struct tempfile::NamedTempFile
source · pub struct NamedTempFile { /* private fields */ }
Expand description
A named temporary file.
The default constructor, NamedTempFile::new()
, creates files in
the location returned by std::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, 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:
- Opening a named temporary file in a world-writable directory.
- Using the
into_temp_path()
and/orinto_parts()
APIs to close the file handle without deleting the underlying file. - 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, such as via std::process::exit()
, by segfaulting, or by
receiving a signal like SIGINT
, then the temporary file
will not be deleted.
Use the tempfile()
function unless you absolutely need a named file.
Implementations§
source§impl NamedTempFile
impl NamedTempFile
sourcepub fn new() -> Result<NamedTempFile>
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:
-
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, Err
is returned.
Examples
Create a named temporary file and write some data to it:
use tempfile::NamedTempFile;
let mut file = NamedTempFile::new()?;
writeln!(file, "Brian was here. Briefly.")?;
sourcepub fn new_in<P: AsRef<Path>>(dir: P) -> Result<NamedTempFile>
pub fn new_in<P: AsRef<Path>>(dir: P) -> Result<NamedTempFile>
Create a new named temporary file in the specified directory.
See NamedTempFile::new()
for details.
sourcepub fn path(&self) -> &Path
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());
sourcepub fn close(self) -> Result<()>
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()?;
sourcepub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<File, PersistError>
pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<File, PersistError>
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 the 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 tempfile::NamedTempFile;
let file = NamedTempFile::new()?;
let mut persisted_file = file.persist("./saved_file.txt")?;
writeln!(persisted_file, "Brian was here. Briefly.")?;
sourcepub fn persist_noclobber<P: AsRef<Path>>(
self,
new_path: P
) -> Result<File, PersistError>
pub fn persist_noclobber<P: AsRef<Path>>( self, new_path: P ) -> Result<File, PersistError>
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 the 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 tempfile::NamedTempFile;
let file = NamedTempFile::new()?;
let mut persisted_file = file.persist_noclobber("./saved_file.txt")?;
writeln!(persisted_file, "Brian was here. Briefly.")?;
sourcepub fn keep(self) -> Result<(File, PathBuf), PersistError>
pub fn keep(self) -> Result<(File, PathBuf), PersistError>
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 tempfile::NamedTempFile;
let mut file = NamedTempFile::new()?;
writeln!(file, "Brian was here. Briefly.")?;
let (file, path) = file.keep()?;
sourcepub fn reopen(&self) -> Result<File>
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 File
s returned by this function; the File
s 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()?;
sourcepub fn as_file_mut(&mut self) -> &mut File
pub fn as_file_mut(&mut self) -> &mut File
Get a mutable reference to the underlying file.
sourcepub fn into_file(self) -> File
pub fn into_file(self) -> File
Convert the temporary file into a std::fs::File
.
The inner file will be deleted.
sourcepub fn into_temp_path(self) -> TempPath
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.
sourcepub fn into_parts(self) -> (File, TempPath)
pub fn into_parts(self) -> (File, 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.
Trait Implementations§
source§impl AsRawFd for NamedTempFile
impl AsRawFd for NamedTempFile
source§impl AsRef<Path> for NamedTempFile
impl AsRef<Path> for NamedTempFile
source§impl Debug for NamedTempFile
impl Debug for NamedTempFile
source§impl From<PersistError> for NamedTempFile
impl From<PersistError> for NamedTempFile
source§fn from(error: PersistError) -> NamedTempFile ⓘ
fn from(error: PersistError) -> NamedTempFile ⓘ
source§impl<'a> Read for &'a NamedTempFile
impl<'a> Read for &'a NamedTempFile
source§fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
1.36.0 · source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read
, except that it reads into a slice of buffers. Read moresource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
)1.0.0 · source§fn read_to_end(&mut self, buf: &mut Vec<u8, Global>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8, Global>) -> Result<usize, Error>
buf
. Read more1.0.0 · source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf
. Read more1.6.0 · source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf
. Read moresource§fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)source§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)cursor
. Read more1.0.0 · source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere Self: Sized,
Read
. Read moresource§impl Read for NamedTempFile
impl Read for NamedTempFile
source§fn read(&mut self, buf: &mut [u8]) -> Result<usize>
fn read(&mut self, buf: &mut [u8]) -> Result<usize>
1.36.0 · source§fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
fn read_vectored(&mut self, bufs: &mut [IoSliceMut<'_>]) -> Result<usize, Error>
read
, except that it reads into a slice of buffers. Read moresource§fn is_read_vectored(&self) -> bool
fn is_read_vectored(&self) -> bool
can_vector
)1.0.0 · source§fn read_to_end(&mut self, buf: &mut Vec<u8, Global>) -> Result<usize, Error>
fn read_to_end(&mut self, buf: &mut Vec<u8, Global>) -> Result<usize, Error>
buf
. Read more1.0.0 · source§fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
fn read_to_string(&mut self, buf: &mut String) -> Result<usize, Error>
buf
. Read more1.6.0 · source§fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
fn read_exact(&mut self, buf: &mut [u8]) -> Result<(), Error>
buf
. Read moresource§fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf(&mut self, buf: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)source§fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
fn read_buf_exact(&mut self, cursor: BorrowedCursor<'_>) -> Result<(), Error>
read_buf
)cursor
. Read more1.0.0 · source§fn by_ref(&mut self) -> &mut Selfwhere
Self: Sized,
fn by_ref(&mut self) -> &mut Selfwhere Self: Sized,
Read
. Read moresource§impl<'a> Seek for &'a NamedTempFile
impl<'a> Seek for &'a NamedTempFile
source§fn seek(&mut self, pos: SeekFrom) -> Result<u64>
fn seek(&mut self, pos: SeekFrom) -> Result<u64>
1.55.0 · source§fn rewind(&mut self) -> Result<(), Error>
fn rewind(&mut self) -> Result<(), Error>
source§impl Seek for NamedTempFile
impl Seek for NamedTempFile
source§fn seek(&mut self, pos: SeekFrom) -> Result<u64>
fn seek(&mut self, pos: SeekFrom) -> Result<u64>
1.55.0 · source§fn rewind(&mut self) -> Result<(), Error>
fn rewind(&mut self) -> Result<(), Error>
source§impl<'a> Write for &'a NamedTempFile
impl<'a> Write for &'a NamedTempFile
source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)1.0.0 · source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored
)source§impl Write for NamedTempFile
impl Write for NamedTempFile
source§fn write(&mut self, buf: &[u8]) -> Result<usize>
fn write(&mut self, buf: &[u8]) -> Result<usize>
source§fn flush(&mut self) -> Result<()>
fn flush(&mut self) -> Result<()>
source§fn is_write_vectored(&self) -> bool
fn is_write_vectored(&self) -> bool
can_vector
)1.0.0 · source§fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
fn write_all(&mut self, buf: &[u8]) -> Result<(), Error>
source§fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
fn write_all_vectored(&mut self, bufs: &mut [IoSlice<'_>]) -> Result<(), Error>
write_all_vectored
)