# IO Project: Grep Command Line project, that uses skills in the previous chapters! `GREP` -> *Globally* search a *Regular* *Expression* and *Print* Take a file + strign argument -> return lines that contain that string and print them ## Objectives - Read Environment Variables - Print Error Messages to console (`stderr` `stdout`) - Use of terminal features - Consolidate Chapters 7->11 - Introduce closures, iterators and trait objects (CHapter 13 & 17) === # Accepting Command Line Arguments `cargo run` will run the program or `/path/to/executable/exec_name.exe` After the executing line, anything we pass separated by spaces, will be treated as arguments: `cargo run arg1 arg2` ## Reading Arguments Passing arguments will not yield anything by default, you have to accept them! `std::env::args` -> function that returns an iterator of the arguments that were given to the program, as well as the execution path relative to where the run command was thrown ```rust let args = std::env::args(); // Iterator of the arguments passed to program ``` Will panic if the arguments have invelid Unicode -> Use `std::env::args_os` if you know you have invalid Unicode, produces `OsString` but varies from platform to platform. `Iterators` will be covered in chapter 13, they are a series of ordered values (a node in a list for example), can use `collect` method to create a collection out of an iterator. ```rust let arg_vec: Vec = args.collect(); ``` ## Saving the Arguments into Variables We can have them into the vector, but when they pile up they will be harder to understand. Use immutable borrowing for this variables, you are reading variables you pass you don't want to change them usually... but you could still borrow it mutably if needed. === # Reading a file ```rust use std::fs; // Work with filesystem to load write files and other operations //... let file_contents = fs::read_to_string(filename) // load file and dump contents into String (not str) .expect("Error message"); // In case of error, panic, could be handled better ``` Not much to add, the argument is passed into the `fs::read_to_string` thus loading if the path to it is correct (accepts relative and full paths).