-
-
Save Measter/2d2c639f32dec94e045a6022652d40ad to your computer and use it in GitHub Desktop.
The Results of the Expressive C++17 Coding Challenge in Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::env; | |
use std::io; | |
use std::io::{BufRead, BufReader, BufWriter, Write}; | |
use std::fs::File; | |
#[derive(Debug)] | |
enum Error { | |
Io(io::Error), | |
Program(&'static str), | |
} | |
impl From<io::Error> for Error { | |
fn from(e: io::Error) -> Error { | |
Error::Io(e) | |
} | |
} | |
impl From<&'static str> for Error { | |
fn from(e: &'static str) -> Error { | |
Error::Program(e) | |
} | |
} | |
fn main() { | |
let mut args = env::args(); | |
// skip the program name | |
args.next().unwrap(); | |
let filename = args.next().unwrap(); | |
let column_name = args.next().unwrap(); | |
let replacement = args.next().unwrap(); | |
let output_filename = args.next().unwrap(); | |
let input = open_input(&filename).unwrap(); | |
replace_column(input, &output_filename, &column_name, &replacement).unwrap(); | |
} | |
fn open_input(path: &str) -> Result<BufReader<File>, Error> { | |
let f = File::open(&path)?; | |
Ok(BufReader::new(f)) | |
} | |
fn open_output(path: &str) -> Result<BufWriter<File>, Error> { | |
let f = File::create(path)?; | |
Ok(BufWriter::new(f)) | |
} | |
fn replace_column(input: BufReader<File>, output_filename: &str, column: &str, replacement: &str) -> Result<(), Error> { | |
let mut lines = input.lines(); | |
let columns = lines.next().ok_or("input is empty")??; | |
let column_number = columns.split(',') | |
.position(|e| e == column) | |
.ok_or("column name doesn’t exist in the input file")?; | |
let mut output = open_output(output_filename)?; | |
writeln!(output, "{}", columns)?; | |
for line in lines { | |
let line = line?; | |
let mut records: Vec<&str> = line.split(',').collect(); | |
records[column_number] = replacement; | |
writeln!(output, "{}", records.join((",")))?; | |
} | |
Ok(()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment