std-function

fs::write: replace a small file

Write an entire byte slice using a convenience operation that may replace existing contents. It is not an atomic transaction or a durability promise. Run only inside a disposable working directory. The fixture must not already exist. Expected stdout (not executed): ok Common mistake: Using fs::write as an atomic crash-safe replacement.

Formal Syntax & Structure

rust syntaxrust
fs::write(path, contents) -> io::Result<()>

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"old").unwrap();    fs::write(&p, b"ok").unwrap();    println!("{}", fs::read_to_string(&p).unwrap());}
Rust Reference