Created
December 28, 2016 01:56
This file contains 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
package main | |
import ( | |
"bufio" | |
"errors" | |
"flag" | |
"fmt" | |
"log" | |
"os" | |
"strings" | |
) | |
func main() { | |
count, err := run() | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(count) | |
} | |
func run() (uint64, error) { | |
flag.Parse() | |
if flag.NArg() < 1 { | |
return 0, errors.New("missing file to search") | |
} else if flag.NArg() < 2 { | |
return 0, errors.New("missing search query") | |
} | |
fpath, query := flag.Arg(0), flag.Arg(1) | |
file, err := os.Open(fpath) | |
if err != nil { | |
return 0, err | |
} | |
scanner := bufio.NewScanner(file) | |
count := uint64(0) | |
for scanner.Scan() { | |
if strings.Contains(scanner.Text(), query) { | |
count++ | |
} | |
} | |
if err := scanner.Err(); err != nil { | |
return 0, err | |
} | |
return count, nil | |
} |
This file contains 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
use std::env; | |
use std::error; | |
use std::fs::File; | |
use std::io::{self, BufRead, Write}; | |
use std::process; | |
type Error = Box<error::Error + Send + Sync>; | |
fn main() { | |
match run() { | |
Ok(count) => println!("{}", count), | |
Err(err) => { | |
let _ = writeln!(&mut io::stderr(), "{}", err); | |
process::exit(1); | |
} | |
} | |
} | |
fn run() -> Result<u64, Error> { | |
let (fpath, query) = match (env::args_os().nth(1), env::args().nth(2)) { | |
(None, _) => return Err(Error::from("missing file to search")), | |
(_, None) => return Err(Error::from("missing search query")), | |
(Some(fpath), Some(query)) => (fpath, query), | |
}; | |
let mut count = 0; | |
let rdr = io::BufReader::new(File::open(fpath)?); | |
for line in rdr.lines() { | |
let line = line?; | |
if line.contains(&query) { | |
count += 1; | |
} | |
} | |
Ok(count) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment