read a file in binary in rust

To read a file as binary data in Rust, you can use the File struct from the standard library and its associated functions.

main.rs
use std::fs::File;
use std::io::Read;

fn main() {
    let mut file = File::open("file.bin").expect("Failed to open file");
    let mut buffer = [0; 1024]; // create a buffer of 1024 bytes
    file.read_exact(&mut buffer).expect("Failed to read file");

    // do something with the binary data in buffer
}
307 chars
11 lines

In this example, we are opening a file called "file.bin" using File::open. We then create a buffer of 1024 bytes and read the file into the buffer using file.read_exact. The &mut prefix on buffer indicates that we are passing a mutable reference to the buffer so that it can be modified by file.read_exact.

After reading the binary data into the buffer, you can do whatever you need to with it. Note that this code assumes that the file is at most 1024 bytes in size; adjust the buffer size as necessary based on the size of the file you are reading.

related categories

gistlibby LogSnag