I'm building a CLI program that takes as an optional final argument the name of a file to read from, which may be left off to read from standard input instead, as with cat
and similar UNIX programs.
Is there any way I could have clap
populate a member of my Cli
struct with something like a Box<dyn BufRead>
initialized from either the file or stdin, or is this just something I'm going to have to handle manually?
Not sure why this was closed as opinion-based, but it seems that the answer to my question is "no". There's no simple way to prepopulate a struct with an open reader on the right thing using only clap's built-in parsing, and I have to do it manually. Case closed.
I wasn't looking for how best to do it manually, just asking if there was a feature I'd overlooked that would let me avoid having to.
You can use an
Option<PathBuf>
and usestdin
whenNone
, everything wrapped into a method (yes, you have to implement it yourself):Playground