Q:

Rust program to read text from a file

belongs to collection: Rust File I/O Programs

0

In this program, we will open an existing file and read text from the file using the read_to_string() method, and print text data.

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 text from a file is given below. The given program is compiled and executed on UBUNTU 18.04 successfully.

// Rust program to read text from a file.

use std::io::Read;

fn main(){
   let mut fileRef = std::fs::File::open("sample.txt").unwrap();
   let mut data = String::new();
   
   fileRef.read_to_string(&mut data).unwrap();
   
   print!("FILE DATA:\n{}", data);
}

Output:

$ rustc main.rs

$ ./main
File Data:
Hello World
Hello India

Explanation:

Here, we opened an existing file "sample.txt" using File::open() function. Then we read text data from the file using the read_to_string() method and printed file data.

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

total answers (1)

Rust program to append data into an existing file... >>
<< Rust program to write text into the file...