Skip to content

Commit 0df97e8

Browse files
authored
Merge pull request #34 from yuk1ty/yuk1ty-working-branch
add 3.6.1
2 parents 97dd1a0 + 04f7d57 commit 0df97e8

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

chapter3/Cargo.toml

+3
Original file line numberDiff line numberDiff line change
@@ -29,3 +29,6 @@ path = "src/3_9_4/main.rs"
2929
[[bin]]
3030
name = "3_9_5"
3131
path = "src/3_9_5/main.rs"
32+
[[bin]]
33+
name = "3_6_1"
34+
path = "src/3_6_1/main.rs"

chapter3/src/3_6_1/main.rs

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
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+
}

0 commit comments

Comments
 (0)