└── cr0c /cr0c: -------------------------------------------------------------------------------- 1 | use rand::seq::SliceRandom; 2 | use std::env; 3 | use std::fs::{self, OpenOptions}; 4 | use std::io::{self, Write}; 5 | 6 | const FILE_PATH: &str = "quotes.txt"; 7 | 8 | fn load_quotes() -> Vec { 9 | match fs::read_to_string(FILE_PATH) { 10 | Ok(content) => content.lines().map(|s| s.to_string()).collect(), 11 | Err(_) => vec![], 12 | } 13 | } 14 | 15 | fn save_quote(quote: String) { 16 | let mut file = OpenOptions::new().append(true).create(true).open(FILE_PATH).expect("Cannot open file"); 17 | writeln!(file, "{}", quote).expect("Failed to write to file"); 18 | } 19 | 20 | fn get_random_quote() { 21 | let quotes = load_quotes(); 22 | if quotes.is_empty() { 23 | println!("No quotes found. Add some first!"); 24 | return; 25 | } 26 | let quote = quotes.choose(&mut rand::thread_rng()).unwrap(); 27 | println!("Random Quote: \"{}\"", quote); 28 | } 29 | 30 | fn main() { 31 | let args: Vec = env::args().collect(); 32 | 33 | if args.len() < 2 { 34 | println!("Usage: quote_gen "); 35 | return; 36 | } 37 | 38 | match args[1].as_str() { 39 | "add" => { 40 | if args.len() < 3 { 41 | println!("Usage: quote_gen add "); 42 | return; 43 | } 44 | let quote = args[2..].join(" "); 45 | save_quote(quote); 46 | println!("Quote added!"); 47 | } 48 | "show" => get_random_quote(), 49 | _ => println!("Unknown command! Use 'add' or 'show'."), 50 | } 51 | } 52 | --------------------------------------------------------------------------------