Function dev_utils::files::read_file

source ·
pub fn read_file(path: &str, filename: &str) -> Result<String, Error>
Expand description

Reads a file given its path and filename.

Arguments

  • path - A string slice representing the path to the file.
  • filename - A string slice representing the name of the file.

Returns

  • A Result where:
    • Ok(String) contains the content of the file as a string if successful.
    • Err(io::Error) contains an error if the file cannot be opened or read.

Example

use std::fs::write;
use dev_utils::files::read_file;
 
let path = "test/";
 
// Create a file to read from.
let file_name = "example.txt";  // Also specify the file format & path.
let content = "Hello, Rust!";
write(format!("{}{}", path ,file_name), content).expect("Unable to write file.");  // Write file to the current directory.
 
// Read the file.
let result = read_file(path, "example.txt");
assert!(result.is_ok());  // Check if the file was read successfully.
assert_eq!(result.unwrap(), "Hello, Rust!");  // Check if the file content is correct.