write to a file in rust

To write to a file in Rust, you can use the std::fs module. The most straightforward way to write data to a file is to use the write function from the std::fs::File struct.

Here's an example:

main.rs
use std::fs::File;
use std::io::prelude::*;

fn main() -> std::io::Result<()> {
    let mut file = File::create("output.txt")?;
    file.write_all(b"Hello, world!")?;
    Ok(())
}
180 chars
9 lines

In this example, File::create creates a new file or truncates an existing file if it already exists. Then, write_all is called on the file variable to write the string "Hello, world!" to the file.

Make sure to include the ? operator after each call that returns a Result, as it propagates any errors that may have occurred. Also, don't forget to import std::io::prelude::* to get access to the write_all method.

related categories

gistlibby LogSnag