Skip to main content

TempFile

Struct TempFile 

Source
pub struct TempFile { /* private fields */ }
Expand description

A named temporary file that will be cleaned automatically after the last reference to it is dropped.

Implementations§

Source§

impl TempFile

Source

pub async fn new() -> Result<Self, Error>

Creates a new temporary file in the default location. When the instance goes out of scope, the file will be deleted.

§Example
let file = TempFile::new().await?;

// The file exists.
let file_path = file.file_path().clone();
assert!(fs::metadata(file_path.clone()).await.is_ok());

// Deletes the file.
drop(file);

// The file was removed.
assert!(fs::metadata(file_path).await.is_err());
Source

pub async fn new_with_name<N: AsRef<str>>(name: N) -> Result<Self, Error>

Creates a new temporary file in the default location. When the instance goes out of scope, the file will be deleted.

§Arguments
  • name - The name of the file to create in the default temporary directory.
§Example
let file = TempFile::new_with_name("new_with_name_example.file").await?;

// The file exists.
let file_path = file.file_path().clone();
assert!(fs::metadata(file_path.clone()).await.is_ok());

// Deletes the file.
drop(file);

// The file was removed.
assert!(fs::metadata(file_path).await.is_err());
Source

pub async fn new_with_uuid(uuid: Uuid) -> Result<Self, Error>

Available on crate feature uuid only.

Creates a new temporary file in the default location. When the instance goes out of scope, the file will be deleted.

§Arguments
  • uuid - A UUID to use as a suffix to the file name.
§Example
let id = uuid::Uuid::new_v4();
let file = TempFile::new_with_uuid(id).await?;

// The file exists.
let file_path = file.file_path().clone();
assert!(fs::metadata(file_path.clone()).await.is_ok());

// Deletes the file.
drop(file);

// The file was removed.
assert!(fs::metadata(file_path).await.is_err());
Source

pub async fn new_in<P: Borrow<Path>>(dir: P) -> Result<Self, Error>

Creates a new temporary file in the specified location. When the instance goes out of scope, the file will be deleted.

The file is created with a collision-resistant, unpredictable name using an exclusive (O_EXCL) create, so it never clobbers an existing file.

§Crate Features
  • uuid - When the uuid crate feature is enabled, a random UUIDv4 is used to generate the temporary file name.
§Arguments
  • dir - The directory to create the file in.
§Example
let path = std::env::temp_dir();
let file = TempFile::new_in(path).await?;

// The file exists.
let file_path = file.file_path().clone();
assert!(fs::metadata(file_path.clone()).await.is_ok());

// Deletes the file.
drop(file);

// The file was removed.
assert!(fs::metadata(file_path).await.is_err());
Source

pub async fn new_with_name_in<N: AsRef<str>, P: Borrow<Path>>( name: N, dir: P, ) -> Result<Self, Error>

Creates a new temporary file in the specified location. When the instance goes out of scope, the file will be deleted.

§Arguments
  • dir - The directory to create the file in.
  • name - The file name to use.
§Example
let path = std::env::temp_dir();
let file = TempFile::new_with_name_in("new_with_name_in_example.file", path).await?;

// The file exists.
let file_path = file.file_path().clone();
assert!(fs::metadata(file_path.clone()).await.is_ok());

// Deletes the file.
drop(file);

// The file was removed.
assert!(fs::metadata(file_path).await.is_err());
Source

pub async fn new_with_uuid_in<P: Borrow<Path>>( uuid: Uuid, dir: P, ) -> Result<Self, Error>

Available on crate feature uuid only.

Creates a new temporary file in the specified location. When the instance goes out of scope, the file will be deleted.

§Arguments
  • dir - The directory to create the file in.
  • uuid - A UUID to use as a suffix to the file name.
§Example
let path = std::env::temp_dir();
let id = uuid::Uuid::new_v4();
let file = TempFile::new_with_uuid_in(id, path).await?;

// The file exists.
let file_path = file.file_path().clone();
assert!(fs::metadata(file_path.clone()).await.is_ok());

// Deletes the file.
drop(file);

// The file was removed.
assert!(fs::metadata(file_path).await.is_err());
Source

pub async fn from_existing<P: Borrow<Path>>( path: P, ownership: Ownership, ) -> Result<Self, Error>

Wraps a new instance of this type around an existing file. If ownership is set to Ownership::Borrowed, this method does not take ownership of the file, i.e. the file will not be deleted when the instance is dropped.

§Arguments
  • path - The path of the file to wrap.
  • ownership - The ownership of the file.
Source

pub fn builder() -> TempFileBuilder

Creates a builder for configuring a new temporary file (prefix, suffix, directory) before creating it.

§Example
let file = TempFile::builder()
    .prefix("log_")
    .suffix(".txt")
    .create()
    .await?;

let name = file.file_path().file_name().unwrap().to_string_lossy().into_owned();
assert!(name.starts_with("log_"));
assert!(name.ends_with(".txt"));
Source

pub fn file_path(&self) -> &PathBuf

Returns the path of the underlying temporary file.

Source

pub async fn open_rw(&self) -> Result<TempFile, Error>

Opens a new TempFile instance in read-write mode.

Source

pub async fn open_ro(&self) -> Result<TempFile, Error>

Opens a new TempFile instance in read-only mode.

Source

pub async fn try_clone(&self) -> Result<TempFile, Error>

Creates a new TempFile instance that shares the same underlying file handle as the existing TempFile instance. Reads, writes, and seeks will affect both TempFile instances simultaneously.

Source

pub fn ownership(&self) -> Ownership

Determines the ownership of the temporary file.

§Example
let file = TempFile::new().await?;
assert_eq!(file.ownership(), Ownership::Owned);
Source

pub fn keep(self) -> PathBuf

Disables automatic deletion and returns the path of the underlying file, turning the temporary file into a permanent one.

This affects every clone that shares the same underlying file: none of them will delete it when dropped.

§Example
let file = TempFile::new().await?;
let path = file.keep();

// The file still exists after the handle is dropped.
assert!(fs::metadata(path.clone()).await.is_ok());
Source

pub async fn persist<P: AsRef<Path>>( self, target: P, ) -> Result<PathBuf, PersistError>

Persists the temporary file by moving it to target, returning the new path. The file will no longer be deleted automatically.

The move is performed with tokio::fs::rename and therefore must stay on the same filesystem (a cross-device move returns an error).

On failure the temporary file is not deleted: it is left at its original location and that path is returned in PersistError::path, so no data is lost on a cross-device or permission error. The caller may re-wrap it with TempFile::from_existing to restore automatic cleanup, or delete it. The local handle is closed before the rename so the move also succeeds on Windows.

§Arguments
  • target - The destination path to move the file to.
§Example
let file = TempFile::new().await?;
let target = std::env::temp_dir().join("persisted_async_tempfile.txt");

let path = file.persist(&target).await.map_err(|e| e.error)?;
assert!(fs::metadata(path.clone()).await.is_ok());
Source

pub async fn drop_async(self)

Asynchronously drops the TempFile, ensuring any resources are properly released. This is useful for explicitly managing the lifecycle of the TempFile in an asynchronous context.

When this is the last reference to an owned file, the file is removed via tokio::fs::remove_file without blocking the runtime. The synchronous Drop remains armed as a backstop, so a cancelled or panicking drop_async still cleans up the file.

§Example
let file = TempFile::new().await?;
let path = file.file_path().to_path_buf();
assert!(path.is_file());

file.drop_async().await; // Explicitly drop the TempFile

assert!(!path.exists());
Source

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

Closes the file, deleting it when this is the last reference to an owned file, and returns the removal result so the caller can observe a deletion failure - unlike the implicit Drop, which has no way to report one. This is the synchronous sibling of drop_async; prefer drop_async inside an async context to avoid blocking the runtime on the unlink syscall.

If other clones still reference the file, cleanup is left to them and Ok(()) is returned. On error the file is left in place and the error is returned; no further automatic deletion is attempted (a synchronous retry of the same failing syscall would be pointless), so the caller owns the file and may inspect, retry, or remove it. This differs from drop_async, whose synchronous Drop backstop is a genuinely different deletion mechanism after a possibly-cancelled async removal.

§Example
let file = TempFile::new().await?;
let path = file.file_path().to_path_buf();

file.close()?; // Explicitly close, surfacing any deletion error.

assert!(!path.exists());

Methods from Deref<Target = File>§

Source

pub async fn sync_all(&self) -> Result<(), Error>

Attempts to sync all OS-internal metadata to disk.

This function will attempt to ensure that all in-core data reaches the filesystem before returning.

§Examples
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.sync_all().await?;

The write_all method is defined on the AsyncWriteExt trait.

Source

pub async fn sync_data(&self) -> Result<(), Error>

This function is similar to sync_all, except that it may not synchronize file metadata to the filesystem.

This is intended for use cases that must synchronize content, but don’t need the metadata on disk. The goal of this method is to reduce disk operations.

Note that some platforms may simply implement this in terms of sync_all.

§Examples
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.sync_data().await?;

The write_all method is defined on the AsyncWriteExt trait.

Source

pub async fn set_len(&self, size: u64) -> Result<(), Error>

Truncates or extends the underlying file, updating the size of this file to become size.

If the size is less than the current file’s size, then the file will be shrunk. If it is greater than the current file’s size, then the file will be extended to size and have all of the intermediate data filled in with 0s.

§Errors

This function will return an error if the file is not opened for writing.

§Examples
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

let mut file = File::create("foo.txt").await?;
file.write_all(b"hello, world!").await?;
file.set_len(10).await?;

The write_all method is defined on the AsyncWriteExt trait.

Source

pub async fn metadata(&self) -> Result<Metadata, Error>

Queries metadata about the underlying file.

§Examples
use tokio::fs::File;

let file = File::open("foo.txt").await?;
let metadata = file.metadata().await?;

println!("{:?}", metadata);
Source

pub async fn try_clone(&self) -> Result<File, Error>

Creates a new File instance that shares the same underlying file handle as the existing File instance. Reads, writes, and seeks will affect both File instances simultaneously.

§Examples
use tokio::fs::File;

let file = File::open("foo.txt").await?;
let file_clone = file.try_clone().await?;
Source

pub async fn set_permissions(&self, perm: Permissions) -> Result<(), Error>

Changes the permissions on the underlying file.

§Platform-specific behavior

This function currently corresponds to the fchmod function on Unix and the SetFileInformationByHandle function on Windows. Note that, this may change in the future.

§Errors

This function will return an error if the user lacks permission change attributes on the underlying file. It may also return an error in other os-specific unspecified cases.

§Examples
use tokio::fs::File;

let file = File::open("foo.txt").await?;
let mut perms = file.metadata().await?.permissions();
perms.set_readonly(true);
file.set_permissions(perms).await?;
Source

pub fn set_max_buf_size(&mut self, max_buf_size: usize)

Set the maximum buffer size for the underlying AsyncRead / AsyncWrite operation.

Although Tokio uses a sensible default value for this buffer size, this function would be useful for changing that default depending on the situation.

§Examples
use tokio::fs::File;
use tokio::io::AsyncWriteExt;

let mut file = File::open("foo.txt").await?;

// Set maximum buffer size to 8 MiB
file.set_max_buf_size(8 * 1024 * 1024);

let mut buf = vec![1; 1024 * 1024 * 1024];

// Write the 1 GiB buffer in chunks up to 8 MiB each.
file.write_all(&mut buf).await?;
Source

pub fn max_buf_size(&self) -> usize

Get the maximum buffer size for the underlying AsyncRead / AsyncWrite operation.

Trait Implementations§

Source§

impl AsRef<File> for TempFile

Source§

fn as_ref(&self) -> &File

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

impl AsyncRead for TempFile

Forwarding AsyncRead to the embedded File

Source§

fn poll_read( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<Result<()>>

Attempts to read from the AsyncRead into buf. Read more
Source§

impl AsyncSeek for TempFile

Forwarding AsyncSeek to the embedded File

Source§

fn start_seek(self: Pin<&mut Self>, position: SeekFrom) -> Result<()>

Attempts to seek to an offset, in bytes, in a stream. Read more
Source§

fn poll_complete( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<u64>>

Waits for a seek operation to complete. Read more
Source§

impl AsyncWrite for TempFile

Forwarding AsyncWrite to the embedded File

Source§

fn poll_write( self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &[u8], ) -> Poll<Result<usize, Error>>

Attempt to write bytes from buf into the object. Read more
Source§

fn poll_flush( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Error>>

Attempts to flush the object, ensuring that any buffered data reach their destination. Read more
Source§

fn poll_shutdown( self: Pin<&mut Self>, cx: &mut Context<'_>, ) -> Poll<Result<(), Error>>

Initiates or attempts to shut down this writer, returning success when the I/O connection has completely shut down. Read more
Source§

fn poll_write_vectored( self: Pin<&mut Self>, cx: &mut Context<'_>, bufs: &[IoSlice<'_>], ) -> Poll<Result<usize, Error>>

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

fn is_write_vectored(&self) -> bool

Determines if this writer has an efficient poll_write_vectored implementation. Read more
Source§

impl Borrow<File> for TempFile

Source§

fn borrow(&self) -> &File

Immutably borrows from an owned value. Read more
Source§

impl BorrowMut<File> for TempFile

Source§

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

Mutably borrows from an owned value. Read more
Source§

impl Debug for TempFile

Source§

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

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

impl Deref for TempFile

Allows implicit treatment of TempFile as a File.

Source§

type Target = File

The resulting type after dereferencing.
Source§

fn deref(&self) -> &Self::Target

Dereferences the value.
Source§

impl DerefMut for TempFile

Allows implicit treatment of TempFile as a mutable File.

Source§

fn deref_mut(&mut self) -> &mut File

Mutably dereferences the value.

Auto Trait Implementations§

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<P, T> Receiver for P
where P: Deref<Target = T> + ?Sized, T: ?Sized,

Source§

type Target = T

🔬This is a nightly-only experimental API. (arbitrary_self_types)
The target type on which the method may be called.
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.