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.
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.
Output:
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