在Rust中,我如何打开一个既可读又可写的文件?
File::open()
是只读的,而File::create()
声称是只写的(还会创建文件,这不是我想要的)。从Rust 1.58版本开始(在我撰写此文时即将发布),你可以这样做:
use std::fs::File;
let mut file = File::options()
.read(true)
.write(true)
.open("foo.txt")?;
在旧版本中,您可以使用OpenOptions
结构打开该文件。它与上面的代码相同,但名称有点奇怪。
use std::fs::OpenOptions;
let mut file = OpenOptions::new()
.read(true)
.write(true)
.open("foo.txt")?;
OpenOptions
对象,然后将其传递给File::open_with
函数。OpenOptions
却具有open
方法,这感觉有些奇怪。 - Matthieu M..open()
而不是.build()
。 - user11877195.build()
。这很奇怪,因为大多数人会期望let mut file = File::open_with_options("foo.txt", OpenOptions::new().read(true).write(true));
。事实上,我刚刚检查了一下,这实际上就是内部实现方式。 - Timmmmstd
过于方便,您始终可以使用libc::fopen
。 - user11877195File::with_options().read(true).write(true).open("foo.txt")
来做很多事情,这是更好的选择。:-) - Timmmm