Q:

Rust program to read a file line by line

belongs to collection: Rust File I/O Programs

0

In this program, we will open a text file and read the file line by line and print the result.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

// 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Rust program to replace a word in a file... >>
<< Rust program to count the total number of lines of...