Last active
January 15, 2017 07:58
-
-
Save zaneli/a865a95e2c66b3c525cf7c951599b77a to your computer and use it in GitHub Desktop.
Rust入門者向けハンズオン #2 https://rust.connpass.com/event/43893/
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate getopts; | |
use std::env; | |
use std::io; | |
use std::io::BufReader; | |
use std::io::prelude::*; | |
use std::fs::File; | |
use getopts::Options; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
let mut opts = Options::new(); | |
opts.optflag("n", "number", "number all output lines"); | |
let matches = match opts.parse(&args[1..]) { | |
Ok(m) => m, | |
Err(f) => panic!(f.to_string()), | |
}; | |
let n = matches.opt_present("n"); | |
for (_, arg) in matches.free.iter().enumerate() { | |
println!("{}", | |
match read_file(arg.clone(), n) { | |
Ok(content) => content, | |
Err(reason) => panic!(reason), | |
}); | |
} | |
} | |
fn read_file(filename: String, n: bool) -> Result<String, io::Error> { | |
let file = File::open(filename)?; | |
let br = BufReader::new(&file); | |
let mut content = String::new(); | |
for (num, line) in br.lines().enumerate() { | |
if n { | |
content.push_str(&format!(" {} {}\n", num, line?)); | |
} else { | |
content.push_str(&format!("{}\n", line?)); | |
} | |
} | |
Ok(content) | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
extern crate regex; | |
use std::env; | |
use std::io; | |
use std::io::BufReader; | |
use std::io::prelude::*; | |
use std::fs::File; | |
use regex::Regex; | |
fn main() { | |
let args: Vec<String> = env::args().collect(); | |
if args.len() > 2 { | |
let pattern = match Regex::new(&args[1]) { | |
Ok(p) => p, | |
Err(e) => panic!(e.to_string()), | |
}; | |
for (_, arg) in args.iter().skip(2).enumerate() { | |
filter_match(arg.clone(), &pattern).unwrap_or_else(|e| { | |
panic!(e.to_string()); | |
}); | |
} | |
} | |
} | |
fn filter_match(filename: String, pattern: &Regex) -> Result<(), io::Error> { | |
let file = File::open(filename)?; | |
let br = BufReader::new(&file); | |
for (_, line) in br.lines().enumerate() { | |
let s = line?; | |
if pattern.is_match(&s) { | |
println!("{}", s); | |
} | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment