rustHow to iterate lines in file in Rust
Iterating lines in a file in Rust is a simple task. The std::fs::File type provides a lines method which returns an iterator over the lines of the file. The following example code reads a file line by line and prints each line to the console:
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() {
let file = File::open("my_file.txt").unwrap();
let reader = BufReader::new(file);
for line in reader.lines() {
println!("{}", line.unwrap());
}
}
Output example
Line 1
Line 2
Line 3
Code explanation
use std::fs::File: imports theFiletype from thestd::fsmodule.let file = File::open("my_file.txt").unwrap(): opens the filemy_file.txtand stores the result in thefilevariable. Theunwrapmethod is used to handle any errors that may occur.let reader = BufReader::new(file): creates aBufReaderfrom thefilevariable.for line in reader.lines(): iterates over the lines of thereadervariable.println!("{}", line.unwrap()): prints each line to the console. Theunwrapmethod is used to handle any errors that may occur.
Helpful links
Related
- How to loop until error in Rust
- How to do a for loop with index in Rust
- How to sleep in a loop in Rust
- How to iterate a map in Rust
- How to iterate string lines in Rust
- Rust parallel loop example
- How to iterate by increment of 2 in Rust
- How to iterate through hashmap keys in Rust
- How to iterate btreemap in Rust
- How to iterate and modify a vector in Rust
More of Rust
- How to use regex lookbehind in Rust?
- How to use regex to match a double quote in Rust?
- How to replace strings using Rust regex?
- Regex example to match multiline string in Rust?
- How to create a Rust regex from a string?
- How to compare two HashSets in Rust?
- How to use regex lookahead in Rust?
- Hashshet example in Rust
- How to get the last element of a slice in Rust?
- How to use Unicode in a regex in Rust?
See more codes...