file_operation/write/async/
fn.rs

1use tokio::fs::{OpenOptions, create_dir_all};
2use tokio::io::{AsyncWriteExt, Error};
3
4/// Writes content to a file asynchronously.
5///
6/// # Arguments
7///
8/// - `&str` - The path to the file.
9/// - `&[u8]` - The content to write.
10///
11/// # Returns
12///
13/// - `Result<(), std::io::Error>` - Ok if successful, Err with error details otherwise.
14pub async fn async_write_to_file(file_path: &str, content: &[u8]) -> Result<(), Error> {
15    if let Some(parent_dir) = std::path::Path::new(file_path).parent() {
16        create_dir_all(parent_dir).await?;
17    }
18    let mut file = OpenOptions::new()
19        .write(true)
20        .create(true)
21        .truncate(true)
22        .open(file_path)
23        .await?;
24    file.write_all(content).await?;
25    Ok(())
26}
27
28/// Appends content to a file asynchronously.
29///
30/// # Arguments
31///
32/// - `&str` - The path to the file.
33/// - `&[u8]` - The content to append.
34///
35/// # Returns
36///
37/// - `Result<(), std::io::Error>` - Ok if successful, Err with error details otherwise.
38pub async fn async_append_to_file(file_path: &str, content: &[u8]) -> Result<(), Error> {
39    if let Some(parent_dir) = std::path::Path::new(file_path).parent() {
40        create_dir_all(parent_dir).await?;
41    }
42    let mut file = OpenOptions::new()
43        .write(true)
44        .create(true)
45        .append(true)
46        .open(file_path)
47        .await?;
48    file.write_all(content).await?;
49    Ok(())
50}