我使用此代码将新行附加到文件末尾:
let text = "New line".to_string();
let mut option = OpenOptions::new();
option.read(true);
option.write(true);
option.create(true);
match option.open("foo.txt") {
Err(e) => {
println!("Error");
}
Ok(mut f) => {
println!("File opened");
let size = f.seek(SeekFrom::End(0)).unwrap();
let n_text = match size {
0 => text.clone(),
_ => format!("\n{}", text),
};
match f.write_all(n_text.as_bytes()) {
Err(e) => {
println!("Write error");
}
Ok(_) => {
println!("Write success");
}
}
f.sync_all();
}
}
它有效,但我认为这太难了。我发现option.append(true);
,但如果我用它代替option.write(true);
我收到“写入错误”。
Using OpenOptions::append http://doc.rust-lang.org/std/fs/struct.OpenOptions.html#method.append是附加到文件的最清晰的方法:
use std::fs::OpenOptions;
use std::io::prelude::*;
fn main() {
let mut file = OpenOptions::new()
.write(true)
.append(true)
.open("my-file")
.unwrap();
if let Err(e) = writeln!(file, "A new line!") {
eprintln!("Couldn't write to file: {}", e);
}
}
从 Rust 1.8.0 开始(commit https://github.com/rust-lang/rust/commit/42f4dd047af2de895df2754f7222b39f10cb6205) and RFC 1252 https://github.com/rust-lang/rfcs/blob/master/text/1252-open-options.md, append(true)
暗示write(true)
。这应该不再是问题了。
Rust 1.8.0之前,必须使用both write
and append
— 第一个允许您将字节写入文件,第二个指定字节将写入的位置。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)