ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT




ADVERTISEMENT



Comments and Discussions!

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.