首页 > 解决方案 > 在 Rust 中以读写模式打开文件

问题描述

在 Rust 中,如何打开文件进行读写File::open()是只读的,而File::create()声明是只写的(并且还会创建不是我想要的文件)。

标签: filerust

解决方案


从 Rust 1.58(我写这篇文章的下一个版本)开始,你可以这样做:

use std::fs::File;

let mut file = File::options()
    .read(true)
    .write(true)
    .open("foo.txt")?;

在旧版本上,您可以使用OpenOptionsstruct 打开文件。它与上面的代码相同,但名称更奇怪。

use std::fs::OpenOptions;

let mut file = OpenOptions::new()
    .read(true)
    .write(true)
    .open("foo.txt")?;

推荐阅读