file_operation/file/write/
async.rs

1use tokio::fs::{OpenOptions, create_dir_all};
2use tokio::io::{AsyncWriteExt, Error};
3
4/// Writes the provided content to a file at the specified `file_path` asynchronously.
5///
6/// - `file_path`: The path to the file where the content will be written.
7/// - `content`: A byte slice (`&[u8]`) containing the content to be written to the file.
8///
9/// - Returns: `Ok(())` if the content was successfully written to the file, or an `Err` with the error details.
10///
11/// # Errors
12/// - If the file cannot be created or opened for writing, an error will be returned. This can happen if:
13///     - There is a problem with the file path (e.g., invalid or inaccessible path).
14///     - There are I/O issues when writing to the file.
15pub async fn async_write_to_file(file_path: &str, content: &[u8]) -> Result<(), Error> {
16    if let Some(parent_dir) = std::path::Path::new(file_path).parent() {
17        create_dir_all(parent_dir).await?;
18    }
19    let mut file = OpenOptions::new()
20        .write(true)
21        .create(true)
22        .truncate(true)
23        .open(file_path)
24        .await?;
25    file.write_all(content).await?;
26    Ok(())
27}
28
29/// Append the provided content to a file at the specified `file_path` asynchronously.
30///
31/// - `file_path`: The path to the file where the content will be written.
32/// - `content`: A byte slice (`&[u8]`) containing the content to be written to the file.
33///
34/// - Returns: `Ok(())` if the content was successfully written to the file, or an `Err` with the error details.
35///
36/// # Errors
37/// - If the file cannot be created or opened for writing, an error will be returned. This can happen if:
38///     - There is a problem with the file path (e.g., invalid or inaccessible path).
39///     - There are I/O issues when writing to the file.
40pub async fn async_append_to_file(file_path: &str, content: &[u8]) -> Result<(), Error> {
41    if let Some(parent_dir) = std::path::Path::new(file_path).parent() {
42        create_dir_all(parent_dir).await?;
43    }
44    let mut file = OpenOptions::new()
45        .write(true)
46        .create(true)
47        .append(true)
48        .open(file_path)
49        .await?;
50    file.write_all(content).await?;
51    Ok(())
52}