German Lashevich
German Lashevich

Reputation: 2453

Is it possible to use the same File for reading and writing?

I'm trying to use the same std::fs::File object for writing and reading, but reading returns an empty string.

I tried to flush, sync_all and seek, but nothing helped. With a new File object I can read the file easily.

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

const FILE_PATH: &str = "test.txt";

fn main() {
    // Create file
    let mut f = std::fs::File::create(FILE_PATH).unwrap();
    f.write_all("foo bar".as_bytes());
    f.seek(std::io::SeekFrom::Start(0));

    // Read from the same descriptor
    let mut content = String::new();
    f.read_to_string(&mut content);
    println!("{:?}", content); // -> ""

    // Read from the other descriptor
    let mut f = std::fs::File::open(FILE_PATH).unwrap();
    let mut content = String::new();
    f.read_to_string(&mut content);
    println!("{:?}", content); // -> "foo bar"
}

Upvotes: 8

Views: 3028

Answers (1)

German Lashevich
German Lashevich

Reputation: 2453

The problem was with File::create — it opens a file in write-only mode. The fix is to use std::fs::OpenOptions:

let mut f = std::fs::OpenOptions::new()
    .create(true)
    .write(true)
    .read(true)
    .open(FILE_PATH)
    .unwrap();

Don't forget to reset the reading position with seek.

Upvotes: 11

Related Questions