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