When writing to file text gets followed by multiple � symbols

In my code I am setting the length of file to 0 using the set_len() method.
Then I am writing to it using the write_all() method.
I was able to recreate the bug using this small program.

use std::io::Write;

fn main() -> Result<(), Box<dyn std::error::Error>>{
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .open("thing.txt")?;

    // Everything writes fine here
    file.write_all(b"PLACEHOLDER")?;

    file.set_len(0)?;

    // File output is �����������PLACEHOLDER-AGAIN
    file.write_all(b"PLACEHOLDER-AGAIN")?;

    Ok(())
}

Am I doing something incorrectly?
I would assume the file output would be PLACEHOLDER-AGAIN

From the docs you linked:

You shrink the file, but your cursor is still 12 bytes in when you write "PLACEHOLDER-AGAIN".

1 Like

According to the set_len docs:

Given this and the behavior you’ve observed, I suspect you need to use seek to move the file cursor to the beginning after calling set_len.

3 Likes

Thank you! Just in case anybody else in the future is reading this. I am pretty sure the working code is:

use std::io::{self, Write, Seek};

fn main() -> Result<(), Box<dyn std::error::Error>>{
    let mut file = std::fs::OpenOptions::new()
        .create(true)
        .write(true)
        .open("thing.txt")?;
    
    file.write_all(b"PLACEHOLDER")?;

    file.set_len(0)?;

    file.seek(io::SeekFrom::Start(0))?;

    // File output is PLACEHOLDER-AGAIN
    file.write_all(b"PLACEHOLDER-AGAIN")?;

    Ok(())
}
1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.