read file in rust bufreader
To read a file in Rust using BufReader
, you can follow these steps:
- Import the necessary modules:
use std::fs::File;
use std::io::{BufRead, BufReader};
- Open the file using
File::open
:
let file = File::open("path/to/file.txt")?;
- Create a
BufReader
instance:
let reader = BufReader::new(file);
- Iterate over the lines of the file using the
lines
method ofBufRead
:
for line in reader.lines() {
let line = line?;
// Process each line here
}
Here's the complete code snippet:
use std::fs::File;
use std::io::{BufRead, BufReader};
fn main() -> std::io::Result<()> {
let file = File::open("path/to/file.txt")?;
let reader = BufReader::new(file);
for line in reader.lines() {
let line = line?;
// Process each line here
}
Ok(())
}
Please note that you need to replace "path/to/file.txt"
with the actual path to your file. Let me know if you need further assistance!