Table of content

File Handling

File Handling in Rust is the way to write or read from a file. File handling can be useful, to create a file and then write on it, save it and then later edit it or read from it.

There are different methods in the Rust library to create, open, remove a file. Also there are additional methods which can be used for file operations.

It may be noted that, In Rust, the structure File, represents a file and allows all read-write operations of a file. The methods is the File struct return a variant of the enum io::Result.

Different methods used in File Operattions

  • open(): This is a static method and opens a file in read-only mode.
  • create(): This is a static method which creates a new file or opens the existing file in write-only mode, if the file_name already exists, but destroys the earlier content of the file.
  • remove_file(): This method removes the file from the file system, however may not be deleted exactly from the storage device.
  • append(): This method sets the option for the append mode of a file.
  • write_all():
  • read_to_string:
Program using create(), write_all() and as_bytes()

The method create() will create a new file, or open the file in write-only mode, destroying the earlier content, if the same file_name already exist.

To use the method create() we have to use import the std::io::Write explicitly by writing the line use std::io::Write; in the beginning of the program. Then we have declared a variable called my_file, and have muted the variable, because, we are going to edit the file.

use std::io::Write;
fn main() {
    let mut my_file = std::fs::File::create("my_document.txt").expect("creation failed");
    my_file.write_all("Hello Chercher.tech".as_bytes()).expect("write failed");
    my_file.write_all("	 Learning is Fun".as_bytes()).expect("write failed");
    println!("The tag line of Chercher.tech has been added, open the file to see :)");
}

Using the method write_all(), we have written the string Hello Chercher.techinto the file called my_document.txt. The method as_bytes() writes new bytes in the newly created file.

Also, at the end of each operation we have tried to handle the errors, using the expect() method, we hav made provision for custom generated errors.

Program Output :

rust-file-create

Now, we can open the file just by writing the file name with the extension in the command prompt and see the content. For that, we simple type- my_document.txt and press enter.

File Output :

rust-file-create-content

As seen in the output, when we try to open the file which is a text document in our case, the file opens in the text editor, which is notepad in our case.

Program to Read a file

Reading a file means reading its content. This can be done by opening the file and copying the content of the file into a string and then print it.

To open the file we use the method open() and then we declare an empty String called file_content. And then we use the function read_to_string() to copy the contents of the file into the string, so that we can easy print it in the console itself.

The program must include the std::io::Read explicitly, that is use std::io::Read at the start of the program.

A program to display or read the contents of a file.

use std::io::Read;
fn main() {
    let mut my_file = std::fs::File::open("my_document.txt").unwrap();
    let mut file_content = String::new();
    my_file.read_to_string( & mut file_content).unwrap();
    print!("The content is: {}", file_content);
}

In the above program, we declared a variable called my_file, and which stores the return value of the open() method. If the open() method encounters an error, such as file_not_found then it will throw an exception, and so the function unwrap() function is used.

The return value open() method must be converted into a string before it can be converted. This using the line let mut file_content - String::new(); an empty string has been created.

And using the line my_file.read_to_string(&mut file_content); the value is copied to the string called file_content.

Program Output :

rust-file-open

Program to remove a file

The method remove_file() removes or delete a file. To use method remove_file(), we have to import std::fs explicitly. This can be done by using the line use::std::fs; in the beginning of the program.

use std::fs;
fn main() {
    fs::remove_file("my_document.txt").expect("could not remove file");
    println!("The file has been removed !");
}

In the above program, the remove_file(), will remove the file my_document.txt, and we have used the method expect() to generate a custom error message in case of any error.

Program Output :

rust-file-delete

We can again use the program to Reading a file, to check whether the file still exist in the directory.

Program to edit a file (Appending a data)

The method append() will append data at the end of the content of a file. The method append() can be used to edit the file. For this, we have to import std::io::Write and std::fs::OpenOptions explicitly at the start of the program.

Thus we need to write the lines- use std::io::Write and use std::fs::OpenOptions at the starting of the program.

A program to append a text at the end of the file contents

use std::fs::OpenOptions;
use std::io::Write;
fn main() {
    let mut file = OpenOptions::new().append(true).open("data.txt").expect("cannot open file");
    file.write_all("Hello ".as_bytes()).expect("write failed");
    file.write_all("\n Chercher.tech".as_bytes()).expect("write failed");
    println!("The company name has been added!");
}

This is important to note that, to edit(that is append a text) to the file, it is necessary to open the file and then concatenate the method append(true). The OpenOption::new() will create set of options, and can be use with different file operating methods. (append() and open() in our case).

Then we have used the method write_all() to append the text Hello and Chercher.tech respectively.

The beauty of the append function is that, it will not erase the previous data inside the file, instead it will just append new text.

Program Output :

rust-file-append-text

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions