file_operation/file/write/
sync.rs

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