|
| 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