简体   繁体   中英

Why does Rust's read_to_end not read a file into a buffer?

The code (adapted from my real problem) is very simple, but I can't figure out what I am missing. It will correctly write to the file. But its output is Buffer: [] , nothing is being read from the file for some reason. What is it?

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

fn main() {
    let mut test_file = std::fs::OpenOptions::new()
        .read(true)
        .write(true)
        .open("testfile.txt")
        .expect("Creating file failed");
    let test_str = String::from("This is only a test!");

    test_file
        .write_all(test_str.as_bytes())
        .expect("Writing file failed");

    let mut buffer: Vec<u8> = Vec::new();
    test_file
        .read_to_end(&mut buffer)
        .expect("Reading file to buffer failed!");

    println!("Buffer: {:?}", &buffer);
}

Reading and writing to a file happens at the current cursor position. When a file is opened the cursor starts at 0 but, after writing, it will be at the end of the data you just wrote. You can move the cursor with seek :

use std::io::{Seek as _, SeekFrom};

test_file.seek(SeekFrom::Start(0)).expect("Failed to seek");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM