How to write to and read from a tempfile?

Modified from the doc example in tempfile - Rust : Rust Playground

use std::io::{self, Read, Write};
use tempfile::tempfile;

fn main() -> io::Result<()> {
    let mut file = tempfile()?;

    writeln!(file, "Brian was here. Briefly.")?;

    let mut s = String::new();
    file.read_to_string(&mut s)?;
    dbg!(s);
    Ok(())
}

Print:

[src/main.rs:11] s = ""

It's not expected, isn't it?

I tried this: Rust Playground

use std::io::{self, Read, Write};
use tempfile::tempfile;

fn main() -> io::Result<()> {
    let mut file = tempfile()?;

    writeln!(&mut file, "Brian was here. Briefly.")?;
    file.write_all(b"Brian was here. Briefly.")?;
    file.flush()?;
    file.sync_all()?;

    {
        let mut file = file.try_clone()?;
        let mut s = String::new();
        file.read_to_string(&mut s)?;
        dbg!(s);
    }
    
    drop(file);
    Ok(())
}

Well, it prints the same empty string [src/main.rs:16] s = "".

On mobile so sorry for the brevity, but try seeking to the beginning of the file before reading / to the end before writing more. (There's a Seek trait.)

2 Likes

Thanks! It works

+   file.seek(SeekFrom::Start(0))?;
    file.read_to_string(&mut s)?;

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.