Rust program to read a file character by character

Rust | File I/O Example: Write a program to read a file character by character.
Submitted by Nidhi, on October 31, 2021

Problem Solution:

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

Program/Source Code:

The source code to read a file character by character is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to read a file 
// character by character

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"));

    for line in file.lines() {
        for ch in line.expect("Unable to read line").chars() {
            println!("Character: {}", ch);
        }
    }
}

Output:

$ rustc main.rs

$ ./main
Character: H
Character: e
Character: l
Character: l
Character: o
Character:  
Character: W
Character: o
Character: r
Character: l
Character: d
Character: H
Character: e
Character: l
Character: l
Character: o
Character:  
Character: I
Character: n
Character: d
Character: i
Character: a

Explanation:

Here, we opened the "sample.txt" file and read the file character by characters and printed the result.

Rust File I/O Programs »






Comments and Discussions!

Load comments ↻






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