How to read a plain text file in Rust

Erick McCollum | 15 Nov 2021

DISCLAIMER: The opinions expressed on this website are solely my own, and they are not associated with my employer, another person, or another organization in any way. All information on this website is provided "as is," without guarantee or warranty of any kind. Read the full disclaimer here.

The Rust programming language is known for its lower-level implementation, similar to that of the C programming language. However, even with this in mind, it is still fairly simple to read the contents of a plain text file using Rust.

For example, assuming that there is a text file named test.txt in the parent directory of a Rust program, one could read the entire contents of that text file using the following code snippet:

    use std::fs;

    fn main() {
        let file_name = "../test.txt";

        println!("Reading the file: {}", file_name);

        let file_content = fs::read_to_string(file_name)
            .expect("Failed to read the file");

        println!("\nFile contents:\n---------------\n{}\n", file_content);

In my example, the above code produced the following output:

    % cargo run

    Reading the file: ../test.txt

    File contents:
    Hello there from test.txt!!!

When compared to a similar approach using the C programming language, the Rust approach is much simpler.

More information may be found in the Rust programming language documentation: Reading a File.

Additionally, the sample code used in this article may be found on my GitHub profile at the following link: code-samples/Rust/read-file.

Copyright © 2019

License | Terms & Conditions | Privacy Policy | Disclaimer