Reputation: 557
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);
}
Upvotes: 2
Views: 1557
Reputation: 58715
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");
Upvotes: 7