Q:

Rust program to read a file character by character

0

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

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now