From e9d1b916708054a354224c6fb9cd85139da47eab Mon Sep 17 00:00:00 2001 From: Adam Carpenter <53hornet@gmail.com> Date: Wed, 27 Mar 2019 15:48:35 -0400 Subject: "Finished chapter 2" --- meap/ch2/src/main.rs | 39 ++++++++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 9 deletions(-) (limited to 'meap/ch2/src') diff --git a/meap/ch2/src/main.rs b/meap/ch2/src/main.rs index 055ec1c..4d16a7a 100644 --- a/meap/ch2/src/main.rs +++ b/meap/ch2/src/main.rs @@ -3,6 +3,12 @@ extern crate clap; use regex::Regex; use clap::{App, Arg}; +use std::fs::File; +use std::io; +use std::io::BufReader; +use std::io::prelude::*; + + //use std::ops::{Add}; fn main() { @@ -69,25 +75,40 @@ fn main() { .help("the pattern to search for") .takes_value(true) .required(true)) + .arg(Arg::with_name("input") + .help("file to search") + .takes_value(true)) .get_matches(); let pattern = args.value_of("pattern").unwrap(); let re = Regex::new(pattern).unwrap(); - let quote = "Every face, every shop, bedroom window, public-house, \ - and\ndark square is a picture feverishly turned--in search \ - of what?\nIt is the same with books. What do we seek through \ - millions of pages?"; - for (index, line) in quote.lines().enumerate() { - match re.find(line) { + let input = args.value_of("input").unwrap_or("-"); + + if input == "-" { + let stdin = io::stdin(); + let reader = stdin.lock(); + process_lines(reader, re); + } + else { + let file = File::open(input).unwrap(); + let reader = BufReader::new(file); + process_lines(reader, re); + } + +} + +fn process_lines(reader: T, re: Regex) { + for line_ in reader.lines() { + let line = line_.unwrap(); + + match re.find(&line) { Some(_) => print!("-> "), None => print!(" "), }; - let line_num = index + 1; - println!("{}: {}", line_num, line); + println!("{}", line); } - } //fn add>(i: T, j: T) -> T { -- cgit v1.2.3