append to a file in rust

To append to a file in Rust, you can use the OpenOptions struct from the std::fs module to open the file in append mode. Then, you can use the write method from the Write trait to write data to the end of the file.

Here's an example:

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

fn main() {
    let mut file = OpenOptions::new()
        .append(true)
        .open("myfile.txt")
        .unwrap();

    let data = "Hello, world!\n";
    file.write(data.as_bytes()).unwrap();
}
245 chars
13 lines

In this example, we create OpenOptions with the append method set to true to open the file in append mode. We then call the open method to open the file, which returns a std::io::Result<File> object that we unwrap to get the file object.

Finally, we call the write method on the file object to write data to the end of the file. Note that we convert the data to a byte slice using the as_bytes method before passing it to the write method.

If successful, this code will append the string "Hello, world!\n" to the end of the file "myfile.txt".

related categories

gistlibby LogSnag