file_io/
save.rs

1use crate::create::create_folder_for_file;
2use std::path::Path;
3
4/// Saves a string to a file at the specified path.
5///
6/// # Arguments
7///
8/// * `content` - The string content to save to the file.
9/// * `path` - The path where the file should be saved (can be a `&str`, [`String`], [`Path`], or
10///   [`std::path::PathBuf`]).
11///
12/// # Panics
13///
14/// If some error is encountered while creating the file or writing to it.
15///
16/// # Note
17///
18/// This function will create the parent folder for the file if it does not already exist.
19///
20/// # Examples
21///
22/// ## Using a string literal
23///
24/// ```
25/// use file_io::save_string_to_file;
26///
27/// let content: &str = "Hello, world!";
28/// let path: &str = "folder/subfolder_11/file_6.txt";
29///
30/// save_string_to_file(content, path);
31/// ```
32///
33/// ## Using a `Path` reference
34///
35/// ```
36/// use file_io::save_string_to_file;
37/// use std::path::Path;
38///
39/// let content: &str = "Hello, world!";
40/// let path: &Path = Path::new("folder/subfolder_12/file_7.txt");
41///
42/// save_string_to_file(content, path);
43/// ```
44pub fn save_string_to_file<P: AsRef<Path>>(content: &str, path: P) {
45    let path = path.as_ref();
46    create_folder_for_file(path);
47    std::fs::write(path, content).unwrap_or_else(|_| panic!("Failed to write to file '{path:?}'."));
48}