In Rust, how do I open a file for reading and writing? File::open()
is read-only, and File::create()
claims is write-only (and also creates files which isn't what I want).
As of Rust 1.58 (the next release as I write this) you can do this:
use std::fs::File;
let mut file = File::options()
.read(true)
.write(true)
.open("foo.txt")?;
On older versions you can use the OpenOptions
struct to open the file. It's the same as the above code but a bit more weirdly named.
use std::fs::OpenOptions;
let mut file = OpenOptions::new()
.read(true)
.write(true)
.open("foo.txt")?;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With