Files
tokio/tokio-fs/src/read.rs
T

36 lines
862 B
Rust
Raw Normal View History

use crate::File;
use tokio_io::AsyncReadExt;
use std::{io, path::Path};
2019-02-20 23:38:49 +01:00
/// Creates a future which will open a file for reading and read the entire
/// contents into a buffer and return said buffer.
///
/// This is the async equivalent of `std::fs::read`.
///
/// # Examples
///
/// ```no_run
/// #![feature(async_await)]
2019-05-14 10:27:36 -07:00
///
/// use tokio::fs;
2019-05-14 10:27:36 -07:00
///
/// # async fn dox() -> std::io::Result<()> {
/// let contents = fs::read("foo.txt").await?;
/// println!("foo.txt contains {} bytes", contents.len());
/// # Ok(())
/// # }
2019-02-20 23:38:49 +01:00
/// ```
pub async fn read<P>(path: P) -> io::Result<Vec<u8>>
2019-02-20 23:38:49 +01:00
where
2019-07-11 11:05:49 -05:00
P: AsRef<Path> + Send + Unpin + 'static,
2019-02-20 23:38:49 +01:00
{
let mut file = File::open(path).await?;
let metadata = file.metadata().await?;
2019-02-20 23:38:49 +01:00
let mut contents = Vec::with_capacity(metadata.len() as usize + 1);
file.read_to_end(&mut contents).await?;
Ok(contents)
2019-02-20 23:38:49 +01:00
}