Rust File I/O Read a file as a Vec


Example

use std::fs::File;
use std::io::Read;

fn read_a_file() -> std::io::Result<Vec<u8>> {
    let mut file = try!(File::open("example.data"));

    let mut data = Vec::new();
    try!(file.read_to_end(&mut data));

    return Ok(data);
}

std::io::Result<T> is an alias for Result<T, std::io::Error>.

The try!() macro returns from the function on error.

read_to_end() is a method of std::io::Read trait, which has to be explicitly used.

read_to_end() does not return data it read. Instead it puts data into the container it's given.