So 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.
Please note this information from the shred manpage.
CAUTION: Note that shred relies on a very important assumption: that the file system overwrites data in place. This is the traditional way to do things, but many modern file system designs do not satisfy this assumption.
Aside from the potential for efficiency improvements, is there any reason that something like this wouldn't meet your needs?
let file_size = std::fs::metadata("file_path")?.len();
let mut rng = rand::rng();
let mut f = std::fs::OpenOptions::new().write(true).open("file_path")?;
for i in 0..file_size {
let rand_byte: u8 = rng.random();
f.write_all(&[rand_byte])?;
}
f.flush()?;