Reading files in Rust, three ways
Rust gives you several levels of control when reading a file. Here are the three I actually use.
The one-liner
For small files, just slurp the whole thing:
1 | use std::fs; |
Buffered lines
For larger files, iterate line by line without loading everything:
1 | use std::fs::File; |
Raw bytes
And when the file is not text at all:
1 | let bytes = std::fs::read("image.png")?; |
That covers 99% of everyday needs. The remaining 1% is memory-mapped IO, which is a story for another post.