Copy Files With Std Fs
Copy a file with fs::copy inside a fallible main, assert the byte count, and compare content line by line before cleaning up both temporary files.
Code
use std::fs;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let source = "payload.txt";
let target = "payload-copy.txt";
fs::write(source, "checksum ok\nbuild 2026-11-21\n")?;
let bytes = fs::copy(source, target)?;
println!("copied {bytes} bytes");
let roundtrip = fs::read_to_string(target)?;
assert_eq!(roundtrip, fs::read_to_string(source)?);
println!("content matches: {} lines", roundtrip.lines().count());
fs::remove_file(source)?;
fs::remove_file(target)?;
Ok(())
}Copy Files With Std Fs: how the code works
Copy Files With Std Fs comes down to the function main.
Fallible operations return Result, and the ? operator short-circuits errors up to the caller.
Caveats
- All it asks for is the runtime — zero packages, zero install.
- Errors travel through
Result; if you drop the?operators while adapting, each call site needs its ownmatch.
Using it
One function carries the logic: fn main() -> Result<(), Box<dyn std::error::Error>>
The output carries the copied, content matches: markers on its lines.
Key statements
fs::write(source, "checksum ok\nbuild 2026-11-21\n")?;
let roundtrip = fs::read_to_string(target)?;
let bytes = fs::copy(source, target)?;
Interactive Tools for This Topic
FAQ
- What happens when a call fails?
- Each fallible operation returns `Result`; nothing is silently discarded.
- What does Copy Files With Std Fs print when run?
- Running the file directly is enough — expect labeled output lines such as `copied`, `content matches:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.