Q:

Rust program to write text into the file

belongs to collection: Rust File I/O Programs

0

In this program, we will create a file and write text into a file using the write_all() method and print an appropriate message.

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

// Rust program to write text into file

use std::io::Write;

fn main() {
   let mut fileRef = std::fs::File::create("sample.txt").expect("create failed");
   
   fileRef.write_all("Hello World\n".as_bytes()).expect("write failed");
   fileRef.write_all("Hello India\n".as_bytes()).expect("write failed");
   
   println!("Text written into file successfully");
}

Output:

$ rustc main.rs

$ ./main
Text written into file successfully

$ cat sample.txt 
Hello World
Hello India

Explanation:

Here, we created a text file "sample.txt" using File::create() function. Then we wrote text data into the file using the write_all() method and printed the appropriate message.

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

total answers (1)

Rust program to read text from a file... >>
<< Rust program to create an empty file...