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.
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.
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.
File::open
" to open the file on the disk. We create BufReader
, and a Vec
(to store the data once read).read_to_end
and pass the vector as a mutable reference argument. Then we use "for" to loop over the vector bytes.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
The file in the example happens to contain 3 letters, the characters "abc." The ASCII values 97, 98 and 99 are those 3 letters.
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.