The source code to read a file line by line is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
// Rust program to read a file line by line
use std::fs::File;
use std::path::Path;
use std::io::{self, BufRead};
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>> where P: AsRef<Path>,
{
let file = File::open(filename)?;
Ok(io::BufReader::new(file).lines())
}
fn main()
{
if let Ok(lines) = read_lines("sample.txt")
{
for line in lines
{
if let Ok(val) = line
{
println!("Line: {}", val);
}
}
}
}
Output:
$ rustc main.rs
$ ./main
Line: Hello World
Line: Hello India
Explanation:
In the above program, we created a function read_lines() and main(). The read_lines() function read lines from text file. In the main() function, we opened the "sample.txt" file and read the lines from the file and printed them.
Program/Source Code:
The source code to read a file line by line is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.
Output:
Explanation:
In the above program, we created a function read_lines() and main(). The read_lines() function read lines from text file. In the main() function, we opened the "sample.txt" file and read the lines from the file and printed them.
need an explanation for this answer? contact us directly to get an explanation for this answer