minigrep.rs/src/main.rs

60 lines
1.4 KiB
Rust
Raw Normal View History

2018-09-18 05:33:56 +00:00
extern crate grep;
use std::env;
use std::fs::File;
use std::io::prelude::*;
2018-09-18 06:24:00 +00:00
use std::process;
use std::error::Error;
2018-09-18 05:33:56 +00:00
struct Config {
query: String,
filename: String,
}
2018-09-18 04:05:47 +00:00
fn main() {
2018-09-18 05:33:56 +00:00
let args: Vec<String> = env::args().collect();
2018-09-18 06:24:00 +00:00
let conf = Config::new(&args).unwrap_or_else(|err| {
println!("Problem parsing arguments: {}", err);
process::exit(1);
});
//let filename = &conf.filename.clone();
2018-09-18 05:33:56 +00:00
2018-09-18 06:24:00 +00:00
if let Err(e) = run(conf) {
println!("Big bad bada boom!\n{:?}", e);
//println!("Big bad bada boom!\n{:?}", e.kind());
//println!("Big bad bada boom!\n{}", e.description());
process::exit(1);
}
}
//fn run(conf: Config) -> Result<(), Box<std::io::Error>>
fn run(conf: Config) -> Result<(), Box<Error>> {
2018-09-18 05:33:56 +00:00
println!("{:?} {:?}", conf.query, conf.filename);
2018-09-18 06:24:00 +00:00
let mut f = File::open(&conf.filename)?;
2018-09-18 05:33:56 +00:00
let mut contents = String::new();
2018-09-18 06:24:00 +00:00
f.read_to_string(&mut contents)?;
2018-09-18 05:33:56 +00:00
println!("Searching for '{}'", conf.query);
println!("In file '{}'", conf.filename);
println!("With text:\n{}", contents);
2018-09-18 06:24:00 +00:00
Ok(())
2018-09-18 05:33:56 +00:00
}
2018-09-18 06:24:00 +00:00
impl Config {
fn new(args: &[String]) -> Result<Config, &'static str> {
if args.len() < 3 {
return Err("too few arguments")
}
Ok(Config {
query: args[1].clone(),
filename: args[2].clone(),
})
2018-09-18 05:33:56 +00:00
}
2018-09-18 04:05:47 +00:00
}