You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I came up with the following. But the pattern-match seems to be a bit tedious; isn't there something easier?
Do you want me, to make a PR?
use clap::{AppSettings,Clap};use std::error::Error;use std::fs::File;use std::io;use std::io::{Read,Write};use std::process;/// A sample-program////// The program is a show-case how to read data either from file or stdin and write data either to/// file or stdout#[derive(Clap)]#[clap(version = "0.1")]#[clap(setting = AppSettings::ColoredHelp)]structOpts{/// Optional output file; default stdout#[clap(short, long)]output:Option<String>,/// Optional input file; default stdininput:Option<String>,}fnmain(){let opts:Opts = Opts::parse();let exit = match(opts.input, opts.output){(None,None) => run(io::stdin(), io::stdout()),(None,Some(f)) => run(io::stdin(),open_output(f)),(Some(f),None) => run(open_input(f), io::stdout()),(Some(fin),Some(fout)) => run(open_input(fin),open_output(fout)),};ifletErr(err) = exit {println!("{}", err);
process::exit(1);}}fnopen_input(f:String) -> File{File::open(f).expect("Could not open input file")}fnopen_output(f:String) -> File{File::create(f).expect("Could not open output file")}fnrun(input:implRead,output:implWrite) -> Result<(),Box<dynError>>{letmut rdr = csv::Reader::from_reader(input);letmut wtr = csv::Writer::from_writer(output);
wtr.write_record(rdr.headers()?)?;for result in rdr.records(){let record = result?;
wtr.write_record(&record)?;}
wtr.flush()?;Ok(())}
It would be great to have an example cli-program with usage:
sample-program --output
if --output is missing, output will be written to stdout; if input-file is missing, input is read from stdin.
Thanks.
The text was updated successfully, but these errors were encountered: