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 theFile
type from thestd::fs
module.let file = File::open("my_file.txt").unwrap()
: opens the filemy_file.txt
and stores the result in thefile
variable. Theunwrap
method is used to handle any errors that may occur.let reader = BufReader::new(file)
: creates aBufReader
from thefile
variable.for line in reader.lines()
: iterates over the lines of thereader
variable.println!("{}", line.unwrap())
: prints each line to the console. Theunwrap
method 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
- Rust for loop range inclusive example
- How to iterate in pairs in Rust
- Rust parallel loop example
- How to iterate over string in Rust
- How to iterate over ndarray rows in Rust
- How to iterate hashset in Rust
- How to iterate linked list in Rust
- How to iterate directory recursively in Rust
More of Rust
- How to replace a capture group using Rust regex?
- How to convert the keys of a Rust HashMap to a vector?
- How to replace all matches using Rust regex?
- How to use regex to match a double quote in Rust?
- How to split a string with Rust regex?
- How to get a capture group using Rust regex?
- How to use regex with bytes in Rust?
- How to get an entry from a HashSet in Rust?
- How to convert a Rust HashMap to a BTreeMap?
- How to use regex to match a group in Rust?
See more codes...