Rust Program - Read and Write a File, Part 2




Rust Program - Read and Write a File

This program is written in Rust and uses the standard library to read and write files.


use std::fs::File;

This line brings the File struct from the std::fs module into scope, allowing it to be used without having to specify the full path.


use std::io::{BufReader, BufRead, BufWriter, Write};

This line brings several structs and traits from the std::io module into scope. BufReader is used to read the contents of a file, BufRead is a trait that allows for reading data from a buffer, BufWriter is used to write to a file, and Write is a trait that allows for writing data to a buffer.


fn main() {

This is the start of the main function, which is the entry point of the program.


let file = File::open("example.txt").unwrap();

This line opens a file named "example.txt" in read-only mode. The File::open() function returns a Result type, which is an enumeration that can either be Ok or Err. The unwrap() method is called on the Result to unwrap it and return the contained file object.


let reader = BufReader::new(file);

This line creates a new buffer reader object, with the opened file as the source of the data.


for line in reader.lines() {

This line starts a loop that iterates over the lines of the file.


let l = line.unwrap();

This line unwraps the line object, which is also a Result type, and assigns the contained string to the variable l.


println!("{}", l);

This line prints the current line to the console.


let file = File::create("output.txt").unwrap();

This line creates a new file named "output.txt" in write-only mode. The File::create() function returns a Result type, which is unwrapped to return the contained file object.


let mut writer = BufWriter::new(file);

This line creates a new buffer writer object, with the created file as the destination for the data.


writer.write_all(b"Hello, world!").unwrap();

This line writes the string "Hello, world!" to the file. The write_all() method is called on the writer object, which writes the data to the file buffer. The method returns a Result type, which is unwrapped to return the contained file object.


}

This is the end of the main function.



Image by 200 Degrees from Pixabay

Comments

Popular posts from this blog

The New ChatGPT Reason Feature: What It Is and Why You Should Use It

Raspberry Pi Connect vs. RealVNC: A Comprehensive Comparison

The Reasoning Chain in DeepSeek R1: A Glimpse into AI’s Thought Process