Follow the steps to implement this recipe:
- Open the main.rs file in the src directory in your preferred text editor.
- Write the code header with the relevant information:
//-- #########################
//-- Task: File system experiments
//-- Author: Vigneshwer.D
//-- Version: 1.0.0
//-- Date: 04 May 17
//-- #########################
- Create the error_chain! macro to define a custom Error and Result type, along with automatic conversions from the standard library error types, after the code header:
#[macro_use]
extern crate error_chain;
use std::fs::File;
use std::io::{Write, BufReader, BufRead};
error_chain! {
foreign_links {
Io(std::io::Error);
}
}
- Define the run method and the quick_main! macro by copying and pasting the following code snippet with the error_chain! macro:
fn run() -> Result<()> {
let path = "lines.txt";
let mut output = File::create(path)?;
write!(output, "Rust is Fun")?;
let input = File::open(path)?;
let buffered = BufReader::new(input);
for line in buffered.lines() {
println!("{}", line?);
}
Ok(())
}
quick_main!(run);
- Save the file and run the project by running the command:
cargo run
We should get the following output on execution of the code: