std-type

OpenOptions: select file access

Configure access before opening. Reading and writing are independent options; creation and truncation are deliberate choices. Run only inside a disposable working directory. The fixture must not already exist. Expected stdout (not executed): Zbc Common mistake: Assuming write access automatically appends or truncates.

Formal Syntax & Structure

rust syntaxrust
OpenOptions::new().read(true).write(true).open(path)

Working Example

Example Snippetrust
fn main() {    use std::fs::{self, File, OpenOptions};    use std::io::{Read, Write};    fs::create_dir("bm-fixture").expect("use a fresh disposable directory");    let p = std::path::Path::new("bm-fixture").join("note.txt");    File::create_new(&p).unwrap().write_all(b"abc").unwrap();    let mut f = OpenOptions::new().read(true).write(true).open(&p).unwrap();    f.write_all(b"Z").unwrap();    println!("{}", fs::read_to_string(&p).unwrap());}
Rust Reference