std-method

File::create_new: exclusive creation

Create a new file with an exclusive name reservation. Existing entries must not be overwritten; handle AlreadyExists rather than checking first and then creating. Run only inside a disposable working directory. The fixture must not already exist. Expected stdout (not executed): true Common mistake: Using exists followed by create as an exclusive creation guarantee.

Formal Syntax & Structure

rust syntaxrust
File::create_new(path) -> io::Result<File>

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();    let e = File::create_new(&p).unwrap_err();    println!("{}", e.kind() == std::io::ErrorKind::AlreadyExists);}
Rust Reference