Kivanc Gunalp 316311e08c Add file I/O exercises (file_io1-3)
Adds three new exercises under exercises/24_file_io/, as proposed in rust-lang/rustlings#2233:

- file_io1: read a whole file with fs::read_to_string and handle the Result.
- file_io2: read/write a file efficiently with BufReader/BufWriter.
- file_io3: build a path with PathBuf and inspect it with .metadata().

Includes matching solutions and a README describing the learning goal of
each exercise.
2026-07-26 15:09:01 +00:00

52 lines
1.1 KiB
Rust

use std::fs;
use std::path::Path;
const TEST_FILE_NAME: &str = "SampleTextFile.txt";
fn main() -> Result<(), std::io::Error> {
create_required_files()?;
let read_str_result = fs::read_to_string(TEST_FILE_NAME);
match read_str_result {
Ok(contents) => {
// TODO : What would be the expected text ?
assert_eq!(, contents);
}
Err(err) => {
eprintln!("File read error. {}", err);
}
}
file_cleanup()?;
Ok(())
}
fn create_required_files() -> Result<(), std::io::Error> {
let file_path = Path::new(TEST_FILE_NAME);
if !file_path.exists() {
fs::write(file_path, "This is the file content.")?;
} else {
println!("File already exist.");
}
Ok(())
}
fn file_cleanup() -> Result<(), std::io::Error> {
let file_path = Path::new(TEST_FILE_NAME);
if file_path.exists() {
fs::remove_file(file_path).inspect(|_| {
println!("Test file {} deleted.", TEST_FILE_NAME);
})?;
} else {
println!(
"No cleanup necessary since {} not exist.",
file_path.display()
);
}
Ok(())
}