File tree Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Expand file tree Collapse file tree 2 files changed +48
-0
lines changed Original file line number Diff line number Diff line change @@ -29,3 +29,6 @@ path = "src/3_9_4/main.rs"
2929[[bin ]]
3030name = " 3_9_5"
3131path = " src/3_9_5/main.rs"
32+ [[bin ]]
33+ name = " 3_6_1"
34+ path = " src/3_6_1/main.rs"
Original file line number Diff line number Diff line change 1+ use std:: io:: { BufRead , BufReader , Result } ;
2+
3+ const SOURCE : & str = r#"1行目
4+ 2行目
5+ 3行目
6+ "# ;
7+
8+ /// 終端文字を気にしながら1行ずつ読み込むパターン。
9+ fn with_eof ( ) -> Result < ( ) > {
10+ let mut reader = BufReader :: new ( SOURCE . as_bytes ( ) ) ;
11+
12+ loop {
13+ let mut buf = String :: new ( ) ;
14+ // `read_line` は `EOF` を検知してもエラーにすることはなく、
15+ // `Ok(0)` が返ってきた時点で `EOF` を検知したことになる。
16+ let num_bytes = reader. read_line ( & mut buf) ?;
17+ print ! ( "{}" , buf) ;
18+
19+ if num_bytes == 0 {
20+ break ;
21+ }
22+ }
23+
24+ Ok ( ( ) )
25+ }
26+
27+ /// 終端を気にせずもっと短く書きたい場合。
28+ fn without_eof ( ) -> Result < ( ) > {
29+ let reader = BufReader :: new ( SOURCE . as_bytes ( ) ) ;
30+ let lines = reader. lines ( ) ;
31+
32+ for line in lines {
33+ let line = line?;
34+ println ! ( "{}" , line) ;
35+ }
36+
37+ Ok ( ( ) )
38+ }
39+
40+ fn main ( ) -> Result < ( ) > {
41+ with_eof ( ) ?;
42+ without_eof ( ) ?;
43+
44+ Ok ( ( ) )
45+ }
You can’t perform that action at this time.
0 commit comments