liveBook · Manning

OpenOptions

As explained in Learn Rust in a Month of Lunches

OpenOptions is a Rust standard-library builder type for configuring how a filesystem file is opened or created.

OpenOptions is a Rust standard-library builder for choosing how a file is opened or created. Configure its options, then call open with a filename; the result is a Result<File>. section 18.3.3

Choose the file behavior with boolean options:

  • read(true) permits reading. section 18.3.3
  • write(true) permits writing. section 18.3.3
  • create(true) creates the file when needed. section 18.3.3
  • create_new(true) creates the file only when it does not already exist; otherwise opening fails. section 18.3.3
  • append(true) adds content instead of replacing existing content, while truncate(true) clears the content on opening. section 18.3.3

Protecting an existing file

use std::fs::File; fn main() -> std::io::Result<()> { let file = File::options() .write(true) .create_new(true) .open("notes.txt")?; Ok(()) } If notes.txt already exists, open returns an AlreadyExists error instead of deleting or replacing it. For an existing file, append(true) can add text safely. section 18.3.3

use std::fs::{write, File};
 
fn main() -> std::io::Result<()> {
    write("calvin_with_dad.txt", 
"Calvin: Dad, how come old photographs are always black and white? Didn't
they have color film back then?
Dad: Sure they did. In fact, those photographs are in color. It's just the
world was black and white then.")?;
 
    let calvin_file = File::options()
        .write(true)
        .create_new(true)
        .open("calvin_with_dad.txt")?;
    Ok(())
}

Inspect a complete File::options example that combines writing, create_new, and Result error propagation. section 18.3.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains builder configuration, key flags, and Result failures through examples without descending into operating-system file-opening internals.
Examples
Uses notes-style file creation, an existing-file error, appending conversation text, and File::options configuration.
What it assumes
Assumes basic File use and introduces OpenOptions through the previously learned builder pattern.
What you can do after
Apply it via std::fs::File::options to open, create, append, read, write, or truncate files deliberately.
How it connects
Connects OpenOptions with File, the builder pattern, filesystem files, and Result-based error handling.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.