file_operation/file/write/
sync.rs

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