Reading Files in Rust

RustRustBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, the open function is introduced as a way to open a file in read-only mode by providing a path to the desired file. The function returns a File object that owns the file descriptor and takes care of closing the file when it is no longer needed.

To use the open function, one needs to import the necessary modules such as std::fs::File, std::io::prelude::*, and std::path::Path. The File::open method is then called with the path as an argument. If the file is successfully opened, the function returns a Result<File, io::Error> object, otherwise, it panics with an error message.

Once the file is opened, its contents can be read using the read_to_string method. This method reads the contents of the file into a string and returns a Result<usize, io::Error>. If the reading operation is successful, the string will contain the file contents. Otherwise, it panics with an error message.

In the example provided, the contents of the hello.txt file are read and printed to the console. The drop trait is used to ensure that the file is closed when the file object goes out of scope.

Note: If the lab does not specify a file name, you can use any file name you want. For example, you can use main.rs, compile and run it with rustc main.rs && ./main.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL rust(("`Rust`")) -.-> rust/BasicConceptsGroup(["`Basic Concepts`"]) rust(("`Rust`")) -.-> rust/DataTypesGroup(["`Data Types`"]) rust(("`Rust`")) -.-> rust/FunctionsandClosuresGroup(["`Functions and Closures`"]) rust(("`Rust`")) -.-> rust/MemorySafetyandManagementGroup(["`Memory Safety and Management`"]) rust(("`Rust`")) -.-> rust/DataStructuresandEnumsGroup(["`Data Structures and Enums`"]) rust(("`Rust`")) -.-> rust/ErrorHandlingandDebuggingGroup(["`Error Handling and Debugging`"]) rust(("`Rust`")) -.-> rust/AdvancedTopicsGroup(["`Advanced Topics`"]) rust/BasicConceptsGroup -.-> rust/variable_declarations("`Variable Declarations`") rust/BasicConceptsGroup -.-> rust/mutable_variables("`Mutable Variables`") rust/DataTypesGroup -.-> rust/string_type("`String Type`") rust/FunctionsandClosuresGroup -.-> rust/function_syntax("`Function Syntax`") rust/FunctionsandClosuresGroup -.-> rust/expressions_statements("`Expressions and Statements`") rust/MemorySafetyandManagementGroup -.-> rust/lifetime_specifiers("`Lifetime Specifiers`") rust/DataStructuresandEnumsGroup -.-> rust/method_syntax("`Method Syntax`") rust/ErrorHandlingandDebuggingGroup -.-> rust/panic_usage("`panic! Usage`") rust/AdvancedTopicsGroup -.-> rust/operator_overloading("`Traits for Operator Overloading`") subgraph Lab Skills rust/variable_declarations -.-> lab-99270{{"`Reading Files in Rust`"}} rust/mutable_variables -.-> lab-99270{{"`Reading Files in Rust`"}} rust/string_type -.-> lab-99270{{"`Reading Files in Rust`"}} rust/function_syntax -.-> lab-99270{{"`Reading Files in Rust`"}} rust/expressions_statements -.-> lab-99270{{"`Reading Files in Rust`"}} rust/lifetime_specifiers -.-> lab-99270{{"`Reading Files in Rust`"}} rust/method_syntax -.-> lab-99270{{"`Reading Files in Rust`"}} rust/panic_usage -.-> lab-99270{{"`Reading Files in Rust`"}} rust/operator_overloading -.-> lab-99270{{"`Reading Files in Rust`"}} end

open

The open function can be used to open a file in read-only mode.

A File owns a resource, the file descriptor and takes care of closing the file when it is droped.

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("hello.txt");
    let display = path.display();

    // Open the path in read-only mode, returns `io::Result<File>`
    let mut file = match File::open(&path) {
        Err(why) => panic!("couldn't open {}: {}", display, why),
        Ok(file) => file,
    };

    // Read the file contents into a string, returns `io::Result<usize>`
    let mut s = String::new();
    match file.read_to_string(&mut s) {
        Err(why) => panic!("couldn't read {}: {}", display, why),
        Ok(_) => print!("{} contains:\n{}", display, s),
    }

    // `file` goes out of scope, and the "hello.txt" file gets closed
}

Here's the expected successful output:

$ echo "Hello World!" > hello.txt
$ rustc open.rs && ./open
hello.txt contains:
Hello World!

(You are encouraged to test the previous example under different failure conditions: hello.txt doesn't exist, or hello.txt is not readable, etc.)

Summary

Congratulations! You have completed the Open lab. You can practice more labs in LabEx to improve your skills.

Other Rust Tutorials you may like