Jakub Kotur | c72d720 | 2020-12-21 17:28:15 +0100 | [diff] [blame^] | 1 | use std::env; |
| 2 | use std::error::Error; |
| 3 | use std::ffi::OsString; |
| 4 | use std::process; |
| 5 | |
| 6 | fn run() -> Result<(), Box<dyn Error>> { |
| 7 | let file_path = get_first_arg()?; |
| 8 | let mut wtr = csv::Writer::from_path(file_path)?; |
| 9 | |
| 10 | wtr.write_record(&[ |
| 11 | "City", |
| 12 | "State", |
| 13 | "Population", |
| 14 | "Latitude", |
| 15 | "Longitude", |
| 16 | ])?; |
| 17 | wtr.write_record(&[ |
| 18 | "Davidsons Landing", |
| 19 | "AK", |
| 20 | "", |
| 21 | "65.2419444", |
| 22 | "-165.2716667", |
| 23 | ])?; |
| 24 | wtr.write_record(&["Kenai", "AK", "7610", "60.5544444", "-151.2583333"])?; |
| 25 | wtr.write_record(&["Oakman", "AL", "", "33.7133333", "-87.3886111"])?; |
| 26 | |
| 27 | wtr.flush()?; |
| 28 | Ok(()) |
| 29 | } |
| 30 | |
| 31 | /// Returns the first positional argument sent to this process. If there are no |
| 32 | /// positional arguments, then this returns an error. |
| 33 | fn get_first_arg() -> Result<OsString, Box<dyn Error>> { |
| 34 | match env::args_os().nth(1) { |
| 35 | None => Err(From::from("expected 1 argument, but got none")), |
| 36 | Some(file_path) => Ok(file_path), |
| 37 | } |
| 38 | } |
| 39 | |
| 40 | fn main() { |
| 41 | if let Err(err) = run() { |
| 42 | println!("{}", err); |
| 43 | process::exit(1); |
| 44 | } |
| 45 | } |