File Reading

Add file reading capability to complete the basic functionality:

I'm nobody! Who are you?
Are you nobody, too?
Then there's a pair of us - don't tell!
They'd banish us, you know.

How dreary to be somebody!
How public, like a frog
To tell your name the livelong day
To an admiring bog!
use std::env;
use std::fs;

fn main() {
    // --snip--
    let args: Vec<String> = env::args().collect();

    let query = &args[1];
    let file_path = &args[2];

    println!("Searching for {query}");
    println!("In file {file_path}");

    let contents = fs::read_to_string(file_path)
        .expect("Should have been able to read the file");

    println!("With text:\n{contents}");
}

Key points:

  • fs::read_to_string() returns Result<String, std::io::Error>
  • Currently using expect() for error handling (will improve in next section)
  • The main function is handling multiple responsibilities (argument parsing, file reading)

Current issues to address:

  1. Poor separation of concerns
  2. Inadequate error handling
  3. No validation of input arguments

The next section addresses these through refactoring.