open a file in rust

To open a file in Rust, you can use the File::open() method provided by the std::fs module which comes with Rust standard library.

main.rs
use std::fs::File;

fn main() {
    let file = File::open("example.txt");
}
76 chars
6 lines

This code will create a file instance (File) that can be used to read or write the file's contents. If the file to open doesn't exist, or you don't have permission to access it, the method will return an error.

You can also use other options provided by the OpenOptions struct to specify how the file should be opened, such as appending data to the end of the existing file or creating a new file if one doesn't already exist.

main.rs
use std::fs::OpenOptions;

fn main() {
    let file = OpenOptions::new()
        .read(true)
        .write(true)
        .create(true)
        .open("example.txt");
}
168 chars
10 lines

This code will create a file instance, just like before. However, this time we specified that the file should be opened for reading and writing, and should be created if it doesn't already exist.

gistlibby LogSnag