ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.