I thought you just open a file and seek to the position you want to overwrite and start writing, but it seems that it only adds bytes at that position. How to I remove bytes from a file or overwrite bytes?
An example:
use std::fs::OpenOptions;
use std::io::{prelude::*, Seek, SeekFrom};
fn main() {
let mut file = OpenOptions::new()
.read(true)
.append(true)
.create(true)
.open("/tmp/file.db")
.unwrap();
let bytes: [u8; 4] = [1, 2, 3, 4];
file.seek(SeekFrom::Start(0)).unwrap();
file.write_all(&bytes).unwrap();
}
Output file before:
00000000: 0102 0304 0a .....
Output file after:
00000000: 0102 0304 0102 0304 0a .........
As you can see, seeking to 0 does not overwrite the 4 bytes already in the file. Instead it prepends them to the file.
Its because you're using append(true)
. From the documentation:
This option, when true, means that writes will append to a file instead of overwriting previous contents. Note that setting
.write(true).append(true)
has the same effect as setting only.append(true)
.
Using write(true)
instead, adds write permissions:
let mut file = OpenOptions::new()
.read(true)
.write(true) // <--------- this
.create(true)
.open("/tmp/file.db")
.unwrap();
..and your code will work as expected.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With