Skip to content

Commit cbd628e

Browse files
authored
Merge pull request #29 from laysakura/section-2_8_1
2.8 Q1: fmt::Write に対して write!() で書式文字列を書き込み、それを一時ファイルに出力し、確認用に読込んで標準出力に表示するプログラム
2 parents 168a531 + bd0ea67 commit cbd628e

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

chapter2/Cargo.toml

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,10 @@ path = "src/2_4_4/client.rs"
2929
name = "server_2_4_4"
3030
path = "src/2_4_4/server.rs"
3131

32+
[[bin]]
33+
name = "2_8_1"
34+
path = "src/2_8_1/main.rs"
35+
3236
[[bin]]
3337
name = "2_8_2"
3438
path = "src/2_8_2/main.rs"

chapter2/src/2_8_1/main.rs

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
//! Write format string to a file using `write!` macro (Go version uses `Fprintf`).
2+
3+
use std::{
4+
env::temp_dir,
5+
fmt,
6+
fs::File,
7+
io::{self, Read, Write},
8+
path::PathBuf,
9+
time::{SystemTime, UNIX_EPOCH},
10+
};
11+
12+
fn mktemp() -> PathBuf {
13+
let mut tempdir = temp_dir();
14+
15+
let tempfile = {
16+
let now = SystemTime::now();
17+
let unixtime = now
18+
.duration_since(UNIX_EPOCH)
19+
.expect("system clock maybe corrupt");
20+
format!("{}-{:09}", unixtime.as_secs(), unixtime.subsec_nanos())
21+
};
22+
23+
tempdir.push(tempfile);
24+
tempdir
25+
}
26+
27+
fn write_fmt<W: fmt::Write>(w: &mut W) {
28+
write!(
29+
w,
30+
"{{}}(\"10\"): {}, {{}}(10): {}, {{:.1}}(10.0): {:.1}\n",
31+
"10", 10, 10.0
32+
)
33+
.expect("wrong format string")
34+
}
35+
36+
fn main() -> io::Result<()> {
37+
let tmp_path = mktemp();
38+
{
39+
let mut contents = String::new();
40+
write_fmt(&mut contents);
41+
let mut f = File::create(&tmp_path)?;
42+
f.write(contents.as_bytes())?;
43+
}
44+
let written_contents = {
45+
let mut f = File::open(&tmp_path)?;
46+
let mut contents = String::new();
47+
let _ = f.read_to_string(&mut contents)?;
48+
contents
49+
};
50+
51+
println!(
52+
"Written to '{}' :",
53+
tmp_path
54+
.to_str()
55+
.expect("should ve safely converted into UTF-8")
56+
);
57+
println!("{}", written_contents);
58+
59+
Ok(())
60+
}

0 commit comments

Comments
 (0)