简单的写法
1#[allow(dead_code)] 2fn output(filename: &str, bytes: &[u8]) -> Result<()> { 3 let mut fp = OpenOptions::new().truncate(true).create(true).write(true).open(Path::new(filename)).chain_err(|| format!("fail to open {}", filename))?; 4 fp.write_all( bytes )?; 5 fp.write_all( &['\n' as u8] )?; 6 fp.flush()?; 7 8 Ok(()) 9}
或者,如下写法更有 Rust 的感觉
1#[allow(dead_code)] 2fn output(filename: &str, bytes: &[u8]) -> Result<()> { 3 OpenOptions::new().truncate(true).create(true).write(true).open(Path::new(filename)).and_then(|mut fp| { 4 fp.write_all( bytes )?; 5 fp.write_all( &['\n' as u8] )?; 6 fp.flush()?; 7 8 Ok(()) 9 }) 10}
引入 BufWriter, 增加写缓冲
1#[allow(dead_code)] 2fn output(filename: &str, bytes: &[u8]) -> Result<()> { 3 let fp = OpenOptions::new().truncate(true).create(true).write(true).open(Path::new(filename)).chain_err(|| format!("fail to open {}", filename))?; 4 let mut writer = BufWriter::with_capacity( 1024*1024*4, fp ); 5 writer.write_all( bytes )?; 6 writer.write_all( &['\n' as u8] )?; 7 writer.flush()?; 8 9 Ok(()) 10}
当 filename == '-' 时,写到标准输出(STDOUT)
1#[allow(dead_code)] 2fn output(filename: &str, bytes: &[u8]) -> Result<()> { 3 let fp = match filename { 4 "-" => Box::new(stdout()) as Box<Write>, 5 filename => { 6 let path = Path::new(filename); 7 //let fp = OpenOptions::new().append(true).create(true).write(true).open(path).unwrap(); 8 let fp = OpenOptions::new().truncate(true).create(true).write(true).open(path).unwrap(); 9 Box::new(fp) as Box<Write> 10 }, 11 }; 12 13 let mut writer = BufWriter::with_capacity( 1024*1024*4, fp ); 14 writer.write_all( bytes )?; 15 writer.write_all( &['\n' as u8] )?; 16 writer.flush()?; 17 18 Ok(()) 19}