ADVERTISEMENT
ADVERTISEMENT

Rust program to count the total number of lines of a text file

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 count the total number of lines in a text file and print the result.

Program/Source Code:

The source code to count the total number of lines of a text file is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to count the total number 
// of lines of a text file

use std::io::{BufRead, BufReader};
use std::fs::File;

pub fn main() {
    let file = BufReader::new(File::open("sample.txt").expect("Unable to open file"));
    let mut cnt  = 0;
    
    for _ in file.lines() {
        cnt = cnt + 1;
    }
    
    println!("Total lines are: {}",cnt);
}

Output:

$ rustc main.rs

$ ./main
Total lines are: 2

$ cat sample.txt 
Hello World
Hello India

Explanation:

Here, we opened the "sample.txt" file and count the total number of lines in the file and printed the result.

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.