I'm going through the command line applications in rust book and trying to do some of the exercises that are there.
Problem: I would like to read the content of a file in memory using BufReader
instead of read_to_string()
, but I'm getting confused on how to use it.
Error message: no method named read_lines found for type std::io::BufReader<&std::path::PathBuf> in the current scope
, which makes sense. Where can I find the methods for BufReader
Tangent question: is BufReader
a class or just an object that was constructed with the new
keyword like in javascript
?
use std::env;
use std::io::BufReader;
use structopt::StructOpt;
#[derive(StructOpt)]
struct Cli {
/// the pattern to look for
pattern: String,
/// the path to the file to read
#[structopt(parse(from_os_str))]
path: std::path::PathBuf,
}
fn help() {
println!(
"usage:
this is just a dummy help
message to see how functions work in rust"
);
}
fn main() {
let args = Cli::from_args();
// [NOTE]: This works
// [ ] Ex:2 Use BufReader instead of read_to_string()
let content = std::fs::read_to_string(&args.path).expect("Could not read file");
for line in content.lines() {
if line.contains(&args.pattern) {
println!("{:#?}", line);
}
}
// [NOTE]: What I am trying to do:
let mut reader = BufReader::new(&args.path);
// .expect("could not read file");
for line in reader.read_lines() {
if line.contains(&args.pattern) {
println!("{:#?}", line);
}
}
}