Struct async_fs::File

source ·
pub struct File { /* private fields */ }
Expand description

An open file on the filesystem.

Depending on what options the file was opened with, this type can be used for reading and/or writing.

Files are automatically closed when they get dropped and any errors detected on closing are ignored. Use the sync_all() method before dropping a file if such errors need to be handled.

NOTE: If writing to a file, make sure to call flush(), sync_data(), or sync_all() before dropping the file or else some written data might get lost!

§Examples

Create a new file and write some bytes to it:

use async_fs::File;
use futures_lite::io::AsyncWriteExt;

let mut file = File::create("a.txt").await?;

file.write_all(b"Hello, world!").await?;
file.flush().await?;

Read the contents of a file into a vector of bytes:

use async_fs::File;
use futures_lite::io::AsyncReadExt;

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

let mut contents = Vec::new();
file.read_to_end(&mut contents).await?;

Implementations§

source§

impl File

source

pub async fn open<P: AsRef<Path>>(path: P) -> Result<File>

Opens a file in read-only mode.

See the OpenOptions::open() function for more options.

§Errors

An error will be returned in the following situations:

  • path does not point to an existing file.
  • The current process lacks permissions to read the file.
  • Some other I/O error occurred.

For more details, see the list of errors documented by OpenOptions::open().

§Examples
use async_fs::File;

let file = File::open("a.txt").await?;
source

pub async fn create<P: AsRef<Path>>(path: P) -> Result<File>

Opens a file in write-only mode.

This method will create a file if it does not exist, and will truncate it if it does.

See the OpenOptions::open function for more options.

§Errors

An error will be returned in the following situations:

  • The file’s parent directory does not exist.
  • The current process lacks permissions to write to the file.
  • Some other I/O error occurred.

For more details, see the list of errors documented by OpenOptions::open().

§Examples
use async_fs::File;

let file = File::create("a.txt").await?;
source

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

Synchronizes OS-internal buffered contents and metadata to disk.

This function will ensure that all in-memory data reaches the filesystem.

This can be used to handle errors that would otherwise only be caught by closing the file. When a file is dropped, errors in synchronizing this in-memory data are ignored.

§Examples
use async_fs::File;
use futures_lite::io::AsyncWriteExt;

let mut file = File::create("a.txt").await?;

file.write_all(b"Hello, world!").await?;
file.sync_all().await?;
source

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

Synchronizes OS-internal buffered contents to disk.

This is similar to sync_all(), except that file metadata may not be synchronized.

This is intended for use cases that must synchronize the contents of the file, but don’t need the file metadata synchronized to disk.

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

§Examples
use async_fs::File;
use futures_lite::io::AsyncWriteExt;

let mut file = File::create("a.txt").await?;

file.write_all(b"Hello, world!").await?;
file.sync_data().await?;
source

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

Truncates or extends the file.

If size is less than the current file size, then the file will be truncated. If it is greater than the current file size, then the file will be extended to size and have all intermediate data filled with zeros.

The file’s cursor stays at the same position, even if the cursor ends up being past the end of the file after this operation.

§Examples
use async_fs::File;

let mut file = File::create("a.txt").await?;
file.set_len(10).await?;
source

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

Reads the file’s metadata.

§Examples
use async_fs::File;

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

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

Changes the permissions on the file.

§Errors

An error will be returned in the following situations:

  • The current process lacks permissions to change attributes on the file.
  • Some other I/O error occurred.
§Examples
use async_fs::File;

let file = File::create("a.txt").await?;

let mut perms = file.metadata().await?.permissions();
perms.set_readonly(true);
file.set_permissions(perms).await?;

Trait Implementations§

source§

impl AsHandle for File

source§

fn as_handle(&self) -> BorrowedHandle<'_>

Borrows the handle. Read more
source§

impl AsRawHandle for File

source§

fn as_raw_handle(&self) -> RawHandle

Extracts the raw handle. Read more
source§

impl AsyncRead for File

source§

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

Attempt to read from the AsyncRead into buf. Read more
source§

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

Attempt to read from the AsyncRead into bufs using vectored IO operations. Read more
source§

impl AsyncSeek for File

source§

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

Attempt to seek to an offset, in bytes, in a stream. Read more
source§

impl AsyncWrite for File

source§

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

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

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

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

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

Attempt to close the object. Read more
source§

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

Attempt to write bytes from bufs into the object using vectored IO operations. Read more
source§

impl Debug for File

source§

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

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

impl From<File> for File

source§

fn from(inner: File) -> File

Converts to this type from the input type.
source§

impl From<OwnedHandle> for File

source§

fn from(fd: OwnedHandle) -> Self

Converts to this type from the input type.

Auto Trait Implementations§

§

impl !Freeze for File

§

impl !RefUnwindSafe for File

§

impl Send for File

§

impl Sync for File

§

impl Unpin for File

§

impl !UnwindSafe for File

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<R> AsyncReadExt for R
where R: AsyncRead + ?Sized,

source§

fn read<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadFuture<'a, Self>
where Self: Unpin,

Reads some bytes from the byte stream. Read more
source§

fn read_vectored<'a>( &'a mut self, bufs: &'a mut [IoSliceMut<'a>] ) -> ReadVectoredFuture<'a, Self>
where Self: Unpin,

Like read(), except it reads into a slice of buffers. Read more
source§

fn read_to_end<'a>( &'a mut self, buf: &'a mut Vec<u8> ) -> ReadToEndFuture<'a, Self>
where Self: Unpin,

Reads the entire contents and appends them to a Vec. Read more
source§

fn read_to_string<'a>( &'a mut self, buf: &'a mut String ) -> ReadToStringFuture<'a, Self>
where Self: Unpin,

Reads the entire contents and appends them to a String. Read more
source§

fn read_exact<'a>(&'a mut self, buf: &'a mut [u8]) -> ReadExactFuture<'a, Self>
where Self: Unpin,

Reads the exact number of bytes required to fill buf. Read more
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§

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

Converts this AsyncRead into a Stream of bytes. Read more
source§

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

Creates an adapter which will chain this stream with another. Read more
source§

fn boxed_reader<'a>(self) -> Pin<Box<dyn AsyncRead + Send + 'a>>
where Self: Sized + Send + 'a,

Boxes the reader and changes its type to dyn AsyncRead + Send + 'a. Read more
source§

impl<S> AsyncSeekExt for S
where S: AsyncSeek + ?Sized,

source§

fn seek(&mut self, pos: SeekFrom) -> SeekFuture<'_, Self>
where Self: Unpin,

Seeks to a new position in a byte stream. Read more
source§

impl<W> AsyncWriteExt for W
where W: AsyncWrite + ?Sized,

source§

fn write<'a>(&'a mut self, buf: &'a [u8]) -> WriteFuture<'a, Self>
where Self: Unpin,

Writes some bytes into the byte stream. Read more
source§

fn write_vectored<'a>( &'a mut self, bufs: &'a [IoSlice<'a>] ) -> WriteVectoredFuture<'a, Self>
where Self: Unpin,

Like write(), except that it writes a slice of buffers. Read more
source§

fn write_all<'a>(&'a mut self, buf: &'a [u8]) -> WriteAllFuture<'a, Self>
where Self: Unpin,

Writes an entire buffer into the byte stream. Read more
source§

fn flush(&mut self) -> FlushFuture<'_, Self>
where Self: Unpin,

Flushes the stream to ensure that all buffered contents reach their destination. Read more
source§

fn close(&mut self) -> CloseFuture<'_, Self>
where Self: Unpin,

Closes the writer. Read more
source§

fn boxed_writer<'a>(self) -> Pin<Box<dyn AsyncWrite + Send + 'a>>
where Self: Sized + Send + 'a,

Boxes the writer and changes its type to dyn AsyncWrite + Send + 'a. 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> Instrument for T

source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
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>,

§

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>,

§

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.
source§

impl<T> WithSubscriber for T

source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more