Home
Rust
File Read Bytes Example
Updated Dec 7, 2023
Dot Net Perls
Read file bytes. For highly optimized file reading in Rust, we often need to act upon the bytes in a file directly. Rust provides ways to load and loop over the bytes in a file.
Use statements. To add file IO in Rust, we need to include the "std::io" and related modules. We also use the Result type in functions that read files.
File create
Vec push
Example. This program reads in a file and stores its data in a Vector of bytes (like a byte array). This is efficient: it does not waste any memory for the file representation in memory.
Start We call "File::open" to open the file on the disk. We create BufReader, and a Vec (to store the data once read).
Then We call read_to_end and pass the vector as a mutable reference argument. Then we use "for" to loop over the vector bytes.
String Array
for
use std::io; use std::io::Read; use std::io::BufReader; use std::fs::File; fn main() -> io::Result<()> { let f = File::open("/Users/sam/file.txt")?; let mut reader = BufReader::new(f); let mut buffer = Vec::new(); // Read file into vector. reader.read_to_end(&mut buffer)?; // Read. for value in buffer { println!("BYTE: {}", value); } Ok(()) }
BYTE: 97 BYTE: 98 BYTE: 99
Output notes. The file in the example happens to contain 3 letters, the characters "abc." The ASCII values 97, 98 and 99 are those 3 letters.
A summary. Reading in byte arrays in Rust is efficient and wastes very little memory or time. For Rust programs where every millisecond matters, this approach is effective.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 7, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen