File Operations in Rust Programming


File operations normally include I/O operations. Rust provides us with different methods to handle all these operations.

Open

Rust provides an open static method that we can use to open a file in read-only mode.

Example

Consider the code shown below:

use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
   // Create a path to the desired file
   let path = Path::new("out.txt");
   let display = path.display();
   let mut file = match File::open(&path) {
      Err(why) => panic!("unable to open {}: {}", display, why),
      Ok(file) => file,
   };
   let mut s = String::new();
   match file.read_to_string(&mut s) {
      Err(why) => panic!("unable to read {}: {}", display, why),
      Ok(_) => print!("{} it contains:
{}", display, s),    }    // `file` goes out of scope, and the "out.txt" file gets    closed }

Output

The output of the above code is

out.txt contains:
Hello World!

Create

The create method opens a file in write-only mode and if the file was already present, then the old content is destroyed.

Example

static RANDOM_TEXT: &str = "Lorem ipsum dolor sit AMEN, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.";
use std::fs::File;
use std::io::prelude::*;
use std::path::Path;
fn main() {
   let path = Path::new("random_text.txt");
   let display = path.display();
   // Open a file in write-only mode, returns `io::Result`
   let mut file = match File::create(&path) {
      Err(why) => panic!("couldn't create {}: {}", display, why),
      Ok(file) => file,
   };
   // Write the `RANDOM_TEXT` string to `file`, returns 
   `io::Result<()>`
   match file.write_all(RANDOM_TEXT.as_bytes()) {
      Err(why) => panic!("couldn't write to {}: {}", display, why),
      Ok(_) => println!("successfully wrote to {}", display),
   }
}

Output

When we run the following command:

cat random_text.txt

The output we get is:

Lorem ipsum dolor sit AMEN, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Updated on: 03-Apr-2021

210 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements