Rust program to read text from a file

Rust | File I/O Example: Write a program to read text from a file.
Last Updated : October 30, 2021

Problem Statement

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.

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.

Rust File I/O Programs »



Advertisement
Advertisement


Comments and Discussions!

Load comments ↻


Advertisement
Advertisement
Advertisement

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