File I/O giving me a headache

The below code in theory should work yet it doesn't why?

use std::{
    fs::OpenOptions,
    io::{Read, Write},
};

fn main() -> std::io::Result<()> {
    let mut file = OpenOptions::new()
        .read(true)
        .write(true)
        .truncate(true)
        .create(true)
        .open("test.txt")?;

    file.write_all(b"maybe worky!")?;
    file.flush()?;

    let mut buf = String::new();
    file.read_to_string(&mut buf)?;
    println!("test.txt\n{}", buf);

    Ok(())
}

You are at the end of the file, so there are no bytes to read. If you want to read all the content of the file just rewind it. Or close and reopen it.

5 Likes

I.e.:

1 Like