rustHow to read file line by line in rust
Reading a file line by line in Rust can be done using the std::fs::File
type and the BufReader
type from the std::io::BufReader
module. To read a file line by line, first open the file in read-only mode using the File::open
method. Then, create a BufReader
from the file handle. Finally, use the BufReader::lines
method to iterate over the lines of the file. The following ## Code example shows how to read a file line by line:
use std::fs::File;
use std::io::{BufReader, BufRead};
fn main() {
let file = File::open("my_file.txt").expect("Unable to open file");
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line.expect("Unable to read line");
println!("{}", line);
}
}
In this example, the File::open
method is used to open the file in read-only mode. Then, a BufReader
is created from the file handle. Finally, the BufReader::lines
method is used to iterate over the lines of the file. For each line, the expect
method is used to unwrap the Result
type and print the line.
Helpful links
Related
- How to write struct to file in Rust
- How to write buffer to file in Rust
- How to write string to file in Rust
- How to write bytes to file in Rust
- How to write line to file in Rust
- How to write to file in Rust
- How to read JSON file in Rust
- How to read binary file in Rust
- How to read all lines from file in Rust
- How to append to file in Rust
More of Rust
- How to use non-capturing groups in Rust regex?
- How to implement PartialEq for a Rust HashMap?
- How to replace a capture group using Rust regex?
- How to use regex to match a double quote in Rust?
- How to use regex to match a group in Rust?
- How to parse JSON string in Rust?
- How to get a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex with bytes in Rust?
- Hashshet example in Rust
See more codes...