1
- // use std::env;
2
1
use std:: fs:: { self , File } ;
3
2
use std:: io:: { self , BufReader , prelude:: * } ;
4
3
use std:: path:: Path ;
5
4
use structopt:: StructOpt ;
6
5
7
6
// Search for a pattern in a file and display the lines that contain it.
8
- #[ derive( StructOpt ) ]
7
+ #[ derive( StructOpt , Debug ) ]
9
8
struct Cli {
10
9
/// The pattern to look for
11
10
pattern : String ,
@@ -15,16 +14,40 @@ struct Cli {
15
14
}
16
15
17
16
fn main ( ) {
17
+ eprintln ! ( "This is an error! :(" ) ;
18
18
let args = Cli :: from_args ( ) ;
19
- if let Ok ( lines) = read_line ( & args. path ) {
20
- for line in lines {
21
- if let Ok ( _line) = line {
22
- if _line. contains ( & args. pattern ) {
23
- println ! ( "{:?}" , _line) ;
19
+ println ! ( "======= args =======" ) ;
20
+ println ! ( "{:#?}" , args) ;
21
+ // Option 1.
22
+ let result = read_line ( & args. path ) ;
23
+ match result {
24
+ Ok ( content) => {
25
+ // println!("file content: {:?}", content);
26
+ for ( index, line) in content. enumerate ( ) {
27
+ if let Ok ( _line) = line {
28
+ if _line. contains ( & args. pattern ) {
29
+ println ! ( "======= match line [{}] =======" , index) ;
30
+ println ! ( "{}" , _line) ;
31
+ }
24
32
}
25
33
}
26
- }
34
+ } ,
35
+ Err ( err) => println ! ( "Oh noes: {}" , err)
27
36
}
37
+
38
+ // read_content(&args.path);
39
+
40
+ // // Option 2.
41
+ // if let Ok(lines) = read_line(&args.path) {
42
+ // for (index, line) in lines.enumerate() {
43
+ // if let Ok(_line) = line {
44
+ // if _line.contains(&args.pattern) {
45
+ // println!("======= match line [{}] =======", index);
46
+ // println!("{}", _line);
47
+ // }
48
+ // }
49
+ // }
50
+ // }
28
51
}
29
52
30
53
/// @see: https://doc.rust-lang.org/stable/rust-by-example/std_misc/file/read_lines.html
@@ -36,6 +59,7 @@ where P: AsRef<Path> {
36
59
37
60
// fn main() {
38
61
// let args = Cli::from_args();
62
+ // // let mut content = fs::read_to_string(&args.path)?;
39
63
// let mut content = fs::read_to_string(&args.path).expect("could not read file");
40
64
41
65
// for line in content.lines() {
@@ -44,3 +68,14 @@ where P: AsRef<Path> {
44
68
// }
45
69
// }
46
70
// }
71
+
72
+ fn read_content < P > ( filename : P ) -> Result < ( ) , Box < dyn std:: error:: Error > >
73
+ where P : AsRef < Path > {
74
+ let result = fs:: read_to_string ( filename) ;
75
+ let content = match result {
76
+ Ok ( content) => { content } ,
77
+ Err ( err) => { return Err ( err. into ( ) ) ; } ,
78
+ } ;
79
+ // println!("file content: {}", content);
80
+ Ok ( ( ) )
81
+ }
0 commit comments