Home »
Rust »
Rust Programs
Rust program to read text from a file
Rust | File I/O Example: Write a program to read text from a file.
Submitted by Nidhi, on October 30, 2021
Problem Solution:
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 »