file_operation/write/async/
fn.rs

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