read write in rust

To read and write in Rust, you can use the std::fs and std::io modules. Here's how you can do it:

Reading from a File: To read from a file in Rust, you can use the File struct and read methods from the std::fs module.

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

fn main() {
    // Open the file in read-only mode
    let mut file = File::open("path/to/file.txt").expect("Failed to open file");

    // Create a buffer to hold the contents of the file
    let mut contents = String::new();

    // Read the file contents into the buffer
    file.read_to_string(&mut contents).expect("Failed to read file");

    // Print the contents of the file
    println!("{}", contents);
}
454 chars
17 lines

Writing to a File: To write to a file in Rust, you can use the File struct and write methods from the std::fs module.

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

fn main() {
    // Open the file in write mode
    let mut file = File::create("path/to/file.txt").expect("Failed to create file");

    // Write to the file
    file.write_all(b"Hello, World!").expect("Failed to write to file");
}
272 chars
11 lines

Make sure to replace "path/to/file.txt" with the actual path to the file you want to read from or write to.

These examples demonstrate the basic usage of reading from and writing to files in Rust. You can explore more advanced features and error handling as per your requirements.

related categories

gistlibby LogSnag