How to clean an old content of a file?

Hello!
I have a problem with writing content to file.
How to clean the old content of the file?

Code:

use std::io::Write;
use std::fs::OpenOptions;
use std::fs;

fn main() {
    const PATH: &str = "myfile.txt";
    let mut f = OpenOptions::new().read(true).write(true).create(true).truncate(true).append(false).open(PATH).unwrap();
    
    let content = "content".to_string();
    f.write_all(&content.as_bytes()).unwrap();
    
    let content = "new content".to_string();
    f.write_all(&content.as_bytes()).unwrap();
    
    let file_content = fs::read_to_string(PATH).expect("Should have been able to read the file");
    println!("{:?}", file_content);
}

Playground

Output log:

"contentnew content"

Expected output log:

"new content"

You don't close, truncate, or rewind the file between the two write_all invocations. Why do you expect it to be overwritten, then?

You could call Seek::rewind() on the file handle between the two calls, which would start writing from the beginning again, without truncating the file. You could also call file.set_len(0) to truncate it.

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.