expression
Create a fresh file without overwriting
Use exclusive creation for a new file in a trusted, disposable directory. An existing name must cause an error. This example creates only its own file, flushes it, closes the handle and removes that file. Do not run in an untrusted shared directory. Tokio is an external dependency; see the proposed Cargo manifest. Expected stdout (not executed): note Common mistake: Using an overwrite-capable open when existing data must be preserved.
Formal Syntax & Structure
rust syntaxrust
tokio::fs::OpenOptions::new().write(true).create_new(true).open(path).awaitWorking Example
Example Snippetrust
#[tokio::main(flavor = "current_thread")]async fn main() { use tokio::io::AsyncWriteExt; let path = "bm-v61-new.txt"; let mut f = tokio::fs::OpenOptions::new().write(true).create_new(true).open(path).await.unwrap(); f.write_all(b"note").await.unwrap(); f.flush().await.unwrap(); drop(f); println!("{}", tokio::fs::read_to_string(path).await.unwrap()); tokio::fs::remove_file(path).await.unwrap();}