Overwriting entire file Cross platform
⚓ Rust 📅 2025-12-20 👤 surdeus 👁️ 1So I had some simple logic for overwriting a file with random bytes
let file_size = std::fs::metadata("file_path")?.len();
// create random number generator
let mut rng = rand::rng();
//open the file and give write permissions
let mut f = std::fs::OpenOptions::new().write(true).open(path_as_str)?;
//for each byte in the file, overwrite it with a random byte
for i in 0..file_size {
let rand_byte: u8 = rng.random();
f.write_at(&[rand_byte], i)?;
}
f.flush();
So this works great as long as the program is for unix, however this won't work for windows.
I've gathered that the correct way of making this cross platform is by using std::io::write::write_all
simplest example i could find:
let mut f = std::fs::OpenOptions::new().write(true).open("./file")?;
f.write_all(b"XXX")?;
f.flush()?;
This works all fine, but i'm having trouble finding out how i could overwrite the entire file length with random bytes using write_all, to be clear I don't want the file to be truncated, I want the entire file to be overwritten so it preserves the filesize.
Thank you, I hope it's clear.
1 post - 1 participant
🏷️ Rust_feed