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()
returnsResult<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:
- Poor separation of concerns
- Inadequate error handling
- No validation of input arguments
The next section addresses these through refactoring.