Writing to a File
seeks the internal cursor forward the length of the input. As such, file.read_to_string
will only return data after the written input. To get back to the beginning, we can file.seek
to a SeekFrom
location. Here's a demo rust app
use std::{fs::OpenOptions,io::{Read, Seek, SeekFrom, Write},};fn main() -> std::io::Result<()> {let mut file = OpenOptions::new().create(true).write(true).read(true).open("foo.txt")?;file.write_all(b"some offset")?;let mut contents_1 = String::new();file.read_to_string(&mut contents_1)?;dbg!(contents_1);file.seek(SeekFrom::Start(0))?;let mut contents_2 = String::new();file.read_to_string(&mut contents_2)?;dbg!(contents_2);Ok(())}