-1

I am wondering is it possible to replace contents without? I have tried this with file.write(), however, it has just been added to the content of the file, not replacing it. Does it possible to replace the contents in a file without deleting the file itself?

the_json_file.write_all(inside_da_file.as_bytes()).expect("Failed to write");I wanted to clear out the file before I write into it.

Taco Cat
  • 9
  • 3

1 Answers1

4

As documented under OpenOptions::truncate:

Sets the option for truncating a previous file.

If a file is successfully opened with this option set it will truncate the file to 0 length if it already exists.

The file must be opened with write access for truncate to work.

Examples

use std::fs::OpenOptions;

let file = OpenOptions::new().write(true).truncate(true).open("foo.txt");

Alternatively, to truncate the file after it has been opened, there's File::set_len followed by Seek::rewind:

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

the_json_file.set_len(0).unwrap();
the_json_file.rewind().unwrap();
the_json_file.write_all(inside_da_file.as_bytes()).expect("Failed to write");
eggyal
  • 122,705
  • 18
  • 212
  • 237