copy a file in rust

To copy a file in Rust, you can use the std::fs::copy function:

main.rs
use std::fs;

fn main() -> std::io::Result<()> {
    let source_file = "path/to/source/file";
    let destination_file = "path/to/destination/file";
    
    fs::copy(source_file, destination_file)?;
    
    Ok(())
}
218 chars
11 lines

In the code above, we first import the std::fs module which contains the copy function. The copy function takes two arguments: the path to the source file and the path to the destination file.

The copy function returns a std::io::Result type, which represents either success or an error in file I/O operations. We use the ? operator to propagate any error that might occur during the file copying operation.

Note that the destination file will be overwritten if it already exists. If you want to copy and rename the file, you can use the std::fs::rename function instead.

gistlibby LogSnag