dash_rs/
lib.rs

1
2/// This module provides utilities for interacting with the file system.
3pub mod filesystem {
4    use std::fs::{self, File};
5    use std::io::{self, Read};
6    use std::path::Path;
7
8    /// Creates a file with a specific name in a specific directory.
9    /// If the directory does not exist, it will be created.
10    /// 
11    /// # Arguments
12    /// * `directory` - The path to the directory where the file should be created.
13    /// * `file_name` - The name of the file to create.
14    /// 
15    /// # Returns
16    /// * `Ok(())` if the file is created successfully.
17    /// * `Err(io::Error)` if an error occurs.
18    pub fn create_file(directory: &str, file_name: &str) -> io::Result<()> {
19        let dir_path = Path::new(directory);
20
21        if !dir_path.exists() {
22            fs::create_dir_all(dir_path)?;
23        }
24
25        let file_path = dir_path.join(file_name);
26
27        File::create(file_path)?;
28
29        Ok(())
30    }
31
32    /// Reads the content of a file in a specific directory and returns it as a string.
33    /// 
34    /// # Arguments
35    /// * `directory` - The path to the directory where the file is located.
36    /// * `file_name` - The name of the file to read.
37    /// 
38    /// # Returns
39    /// * `Ok(String)` containing the file's content.
40    /// * `Err(io::Error)` if an error occurs.
41    pub fn read_file(directory: &str, file_name: &str) -> io::Result<String> {
42        let file_path = Path::new(directory).join(file_name);
43
44        // Open the file and read its contents
45        let mut file = File::open(file_path)?;
46        let mut content = String::new();
47        file.read_to_string(&mut content)?;
48
49        Ok(content)
50    }
51
52    /// Deletes a file with a specific name in a specific directory.
53    /// 
54    /// # Arguments
55    /// * `directory` - The path to the directory where the file is located.
56    /// * `file_name` - The name of the file to delete.
57    /// 
58    /// # Returns
59    /// * `Ok(())` if the file is deleted successfully.
60    /// * `Err(io::Error)` if an error occurs.
61    pub fn delete_file(directory: &str, file_name: &str) -> io::Result<()> {
62        let file_path = Path::new(directory).join(file_name);
63
64        // Delete the file
65        fs::remove_file(file_path)?;
66
67        Ok(())
68    }
69
70}