Rust Program to Count number of lines present in the file


Count number of lines present in the file

Rust Programming Language


Count number of lines present in the file


Problem


Rust program that counts the number of lines in a given file.

Input


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

fn main() -> std::io::Result<()> {
    let file = File::open("filename.txt")?;
    let reader = BufReader::new(file);
    let mut count = 0;

    for line in reader.lines() {
        count += 1;
    }

    println!("Number of lines: {}", count);
    Ok(())
}{codeBox}


Output


Number of lines: 10{codeBox}


Explanation


This program uses the std::io::BufReader to efficiently read the file line by line and count the number of lines present in the file. Note that you will need to replace "filename.txt" with the path to the file you want to count the lines of.

Post a Comment