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
