Rust IO

Let us look at Rust IO. To read a file.

use std::io::Read;

fn main(){

   let mut file = std::fs::File::open("input.txt").unwrap();

   let mut contents = String::new();

   file.read_to_string(&mut contents).unwrap();

   print!("{}", contents);

}


 

The code above is compiled using the below command.

 rustc read_file.rs

The output will be as below:

apples-MacBook-Air:io bhagvan.kommadi$ ls

input.txt	read_file	read_file.rs

apples-MacBook-Air:io bhagvan.kommadi$ ./read_file 

line 1

 

Now let us look at the opening a file and writing to a file by adding new line.

use std::fs::OpenOptions;

use std::io::Write;

fn main() {

   let mut file = OpenOptions::new().append(true).open("initial.txt").expect(

      "unable to open file");

   file.write_all("adding new line".as_bytes()).expect("write error");

   file.write_all("\n next line".as_bytes()).expect("write error");

   println!("file adding success");

}

 

The code above can be compiled using :

 rustc append_file.rs

 

The output will be :

apples-MacBook-Air:io bhagvan.kommadi$ ls

append_file initial.txt read_file

append_file.rs input.txt read_file.rs

apples-MacBook-Air:io bhagvan.kommadi$ ./append_file 

file adding success

 

The initial file had :

line 1

 

After the execution of append_file.rs, the new file will be:

 

line 1

adding new line

 next line

~          

~          

 

 

 

 

 

Leave a comment