Skip to content

Instantly share code, notes, and snippets.

@hrysd
Created October 15, 2016 08:24
Show Gist options
  • Save hrysd/8cd1c9322aeff3ce226f13075bb78f90 to your computer and use it in GitHub Desktop.
Save hrysd/8cd1c9322aeff3ce226f13075bb78f90 to your computer and use it in GitHub Desktop.
cat
[package]
name = "cat"
version = "0.1.0"
authors = ["hrysd"]
[dependencies]
getopts = "0.2"
extern crate getopts;
use getopts::Options;
use std::env;
use std::io;
use std::io::prelude::*;
use std::fs::File;
fn read_file(filename: String) -> Result<String, io::Error> {
let mut file = try!(File::open(filename));
let mut content = String::new();
try!(file.read_to_string(&mut content));
Ok(content)
}
fn print_line_with_numbers(filename: String) {
let body = match read_file(filename) {
Ok(content) => content,
Err(reason) => panic!("{}", reason)
};
let splitted = body.split("\n");
//println!("{:?}", splitted.count());
let mut formatted: Vec<String> = Vec::new();
for (index, line) in splitted.enumerate() {
formatted.push(format!("{}: {}", index , line));
}
println!("{}", formatted.join("\n"))
}
fn main() {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.optflag("n", "", "Number the output lines, starting at 1.");
let matches = match opts.parse(&args[1..]) {
Ok(m) => m,
Err(f) => panic!(f.to_string())
};
if matches.opt_present("n") {
print_line_with_numbers(args[1].clone())
} else {
println!("{}", read_file(args[1].clone()).unwrap())
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment