Home
Map
Rust
File Read Bytes Example
This page was last reviewed on 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 tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 7, 2023 (edit).
Home
Changes
© 2007-2024 Sam Allen.