Rust program to read a file line by line

Rust | File I/O Example: Write a program to count the total number of lines of a text file.
Submitted by Nidhi, on October 31, 2021

Problem Solution:

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

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.

Rust File I/O Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.