expression

Exclusive destination copy using io::copy

Open the source then reserve a fresh destination atomically; the copy itself can fail after writing a prefix. Report the error and clean up only your own destination. Use a fresh disposable working directory exclusively controlled by this program. Expected stdout (not executed): 5 Common mistake: Checking destination existence and then opening with truncation.

Formal Syntax & Structure

rust syntaxrust
File::create_new(destination); io::copy(&mut source, &mut destination)

Working Example

Example Snippetrust
fn main() {    use std::fs::{self, File};    use std::io::{Read, Write};    fs::create_dir("bm-fixture").expect("fresh working directory required");    let p = std::path::Path::new("bm-fixture").join("note.txt");    File::create_new(&p).unwrap().write_all(b"hello").unwrap();    let mut src = File::open(&p).unwrap();    let q = p.with_file_name("copy.txt");    let mut dst = File::create_new(&q).unwrap();    let n = std::io::copy(&mut src, &mut dst).unwrap();    println!("{n}");}
Rust Reference