| 1 | use crate::io; |
| 2 | use crate::path::Path; |
| 3 | use crate::task::spawn_blocking; |
| 4 | use crate::utils::Context as _; |
| 5 | |
| 6 | /// Reads the entire contents of a file as raw bytes. |
| 7 | /// |
| 8 | /// This is a convenience function for reading entire files. It pre-allocates a buffer 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 a string, use [`read_to_string`] instead. |
| 13 | /// |
| 14 | /// This function is an async version of [`std::fs::read`]. |
| 15 | /// |
| 16 | /// [`read_to_string`]: fn.read_to_string.html |
| 17 | /// [`std::fs::read`]: https://doc.rust-lang.org/std/fs/fn.read.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 | /// * Some other I/O error occurred. |
| 26 | /// |
| 27 | /// # Examples |
| 28 | /// |
| 29 | /// ```no_run |
| 30 | /// # fn main() -> std::io::Result<()> { async_std::task::block_on(async { |
| 31 | /// # |
| 32 | /// use async_std::fs; |
| 33 | /// |
| 34 | /// let contents = fs::read("a.txt" ).await?; |
| 35 | /// # |
| 36 | /// # Ok(()) }) } |
| 37 | /// ``` |
| 38 | pub async fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> { |
| 39 | let path: PathBuf = path.as_ref().to_owned(); |
| 40 | spawn_blockingJoinHandle, …>>(move || { |
| 41 | std::fs::read(&path).context(|| format!("could not read file ` {}`" , path.display())) |
| 42 | }) |
| 43 | .await |
| 44 | } |
| 45 | |