Kivanc Gunalp 4e9b5735ad Use more idiomatic Rust in file_io2/file_io3
- file_io2: replace the manual line_number counter with
  .lines().enumerate(), and replace
  buffered_file_writer.write(format!(...).as_bytes()) with writeln!,
  which both formats and guarantees a complete write (write_fmt loops
  internally, unlike a single Write::write call).
- file_io3: replace the manual match on file_path.parent() with
  .ok_or_else(...)? for a more idiomatic Option-to-Result conversion.

Verified locally: both solutions compile under edition 2024, clippy is
silent, and running them still produces identical output (3 lines
processed / 117-byte file, non-readonly permissions) with no leftover
files.
2026-07-26 15:48:35 +00:00

74 lines
2.2 KiB
Rust

use std::fs;
use std::io::{BufRead, BufReader, BufWriter, Write};
use std::path::Path;
const TEST_INPUT_FILE_NAME: &str = "MultiLineTextFile.txt";
const TEST_OUTPUT_FILE_NAME: &str = "MultiLineOutputFile.txt";
const SAMPLE_TEXT: &str = "This is the first line of the text.
This is the second line.
And this is the third and the last line.";
fn main() -> Result<(), std::io::Error> {
create_required_files()?;
let input_file = fs::File::open(TEST_INPUT_FILE_NAME).inspect_err(|err| {
eprintln!("{} file open error {:?}", TEST_INPUT_FILE_NAME, err);
})?;
let buffered_input_file = BufReader::new(input_file);
let output_file = fs::File::create(TEST_OUTPUT_FILE_NAME).inspect_err(|err| {
eprintln!("{} file open error {:?}", TEST_OUTPUT_FILE_NAME, err);
})?;
let mut buffered_file_writer = BufWriter::new(output_file);
let mut lines_processed = 0;
for (index, line) in buffered_input_file.lines().enumerate() {
let line = line.inspect_err(|err| {
eprintln!("{} line parse error {:?}", TEST_INPUT_FILE_NAME, err);
})?;
let line_number = index + 1;
writeln!(buffered_file_writer, "Line {} : {}", line_number, line).inspect_err(|err| {
eprintln!("{} line write error {:?}", TEST_INPUT_FILE_NAME, err);
})?;
lines_processed = line_number;
}
println!("{} : lines processed", lines_processed);
file_cleanup()
}
fn create_required_files() -> Result<(), std::io::Error> {
let file_path = Path::new(TEST_INPUT_FILE_NAME);
if !file_path.exists() {
fs::write(file_path, SAMPLE_TEXT).inspect_err(|err| {
eprintln!("Couldn't create the test file : {}", err);
})?;
}
Ok(())
}
fn file_cleanup() -> Result<(), std::io::Error> {
let file_names = vec![TEST_INPUT_FILE_NAME, TEST_OUTPUT_FILE_NAME];
for file_name in file_names {
let file_path = Path::new(file_name);
if file_path.exists() {
fs::remove_file(file_path).inspect(|_| {
println!("Test file {} removed", file_name);
})?;
} else {
println!("No cleanup necessary since {} not exist.", file_name);
}
}
Ok(())
}