create a file in rust

To create a file in Rust, you can use the std::fs::File struct:

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

fn main() -> std::io::Result<()> {
    let file = File::create("file.txt")?;
    // do something with the file
    Ok(())
}
144 chars
8 lines

In this example, we use the create method of the File struct to create a new file called "file.txt". The ? operator is used to propagate any errors that might occur during file creation.

Alternatively, you can use the std::fs::OpenOptions struct to create a file with specific options:

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

fn main() -> std::io::Result<()> {
    let file = OpenOptions::new()
               .write(true)
               .create(true)
               .open("file.txt")?;
    // do something with the file
    Ok(())
}
235 chars
11 lines

In this example, we use the new method of the OpenOptions struct to create a new options object, and then chain some options to it. The open method is then used to create the file with the specified options.

related categories

gistlibby LogSnag