RUST EXCERCISE - STORE TEXT IN TEXT FILE

 STORE TEXT IN TEXT FILE

EXCERCISE: 

  • Storing text in a text file.

SOLUTION:

  • Create a new binary package called notes:
  • cargo run --build notes
  • Add rust analyser to vscode settings.json.
  • Go to crates.io, search for chrono.
  • Copy their version and paste it in cargo.toml.
  • chrono = "0.4.23"
    
  • Run cargo-watch with a parameter YOUR NOTES passed into it:
  • cargo-watch -qc -x 'run -- "YOUR NOTE"' -i "notes.txt" -x clippy
  • The above command makes sure not to rerun your code again and again whenever there is a change in notes.txt.

  • #![deny(clippy::all)]
    use std::env;
    use std::fs::OpenOptions;
    use std::io::prelude::*;
    use std::process;
    
    fn main() -> Result<(), Box<dyn std::error::Error>> {
      let args: Vec<String> = env::args().collect();
      if args.len() < 2 {
        Err("Usage: notes your_note_goes_here")?;
        process::exit(1);
      }
      let notes = args[1].clone();
      let now = chrono::Local::now().format("%Y-%m-%d").to_string();
      let mut file = OpenOptions::new()
          .create(true)
          .write(true)
          .append(true)
          .open("notes.txt")
          .unwrap();
      file.write_all(b"<!--")?;
      file.write_all(now.as_bytes())?;
      file.write_all(b"-->\n")?;
      file.write_all(notes.as_bytes())?;
      file.write_all(b"\n\n")?;
      Ok(())
    }

Comments