Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you modify a file's contents instead of prepending to the file in Rust?

Tags:

rust

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.

like image 274
Fallen Avatar asked Jun 04 '18 22:06

Fallen


1 Answers

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.

like image 157
Simon Whitehead Avatar answered Oct 11 '22 20:10

Simon Whitehead