November 2017
Intermediate to advanced
264 pages
5h 45m
English
Reading in a file in memory with read_to_string might not be that clever with large files, because that would use a large chunk of memory. In that case, it is much better to use the buffered reading provided by BufReader and BufRead from std::io:; this way lines are read in and processed one by one.
In the following example, a file with numerical information is processed. Each line contains two fields, an integer, and a float, separated by a space:
// code from Chapter 11/code/reading_text_file.rs:
use std::io::{BufRead, BufReader};
use std::fs::File;
fn main() {
let file = BufReader::new(File::open("numbers.txt").unwrap()); let pairs: Vec<_> = file.lines().map(|line| { let line = line.unwrap(); let line = line.trim(); ...Read now
Unlock full access