First implementation of grrs
After the last chapter on command line arguments,we have our input data,and we can start to write our actual tool.Our main
function only contains this line right now:
let args = Cli::from_args();
Let’s start by opening the file we got.
let content = std::fs::read_to_string(&args.path)
.expect("could not read file");
Aside:See that .expect
method here?This is a shortcut function to quit that will make the program exit immediatelywhen the value (in this case the input file)could not be read.It’s not very pretty,and in the next chapter on Nicer error reportingwe will look at how to improve this.
Now, let’s iterate over the linesand print each one that contains our pattern:
for line in content.lines() {
if line.contains(&args.pattern) {
println!("{}", line);
}
}
Give it a try: cargo run — main src/main.rs
should work now!
Exercise for the reader:This is not the best implementation:It will read the whole file into memory– however large the file may be.Find a way to optimize it!(One idea might be to use a BufReader
instead of read_to_string()
.)