async_std/fs/
read_to_string.rs

1use crate::io;
2use crate::path::Path;
3use crate::task::spawn_blocking;
4use crate::utils::Context as _;
5
6/// Reads the entire contents of a file as a string.
7///
8/// This is a convenience function for reading entire files. It pre-allocates a string based on the
9/// file size when available, so it is typically faster than manually opening a file and reading
10/// from it.
11///
12/// If you want to read the contents as raw bytes, use [`read`] instead.
13///
14/// This function is an async version of [`std::fs::read_to_string`].
15///
16/// [`read`]: fn.read.html
17/// [`std::fs::read_to_string`]: https://doc.rust-lang.org/std/fs/fn.read_to_string.html
18///
19/// # Errors
20///
21/// An error will be returned in the following situations:
22///
23/// * `path` does not point to an existing file.
24/// * The current process lacks permissions to read the file.
25/// * The contents of the file cannot be read as a UTF-8 string.
26/// * Some other I/O error occurred.
27///
28/// # Examples
29///
30/// ```no_run
31/// # fn main() -> std::io::Result<()> { async_std::task::block_on(async {
32/// #
33/// use async_std::fs;
34///
35/// let contents = fs::read_to_string("a.txt").await?;
36/// #
37/// # Ok(()) }) }
38/// ```
39pub async fn read_to_string<P: AsRef<Path>>(path: P) -> io::Result<String> {
40    let path = path.as_ref().to_owned();
41    spawn_blocking(move || {
42        std::fs::read_to_string(&path)
43            .context(|| format!("could not read file `{}`", path.display()))
44    })
45    .await
46}