I want to write programs that behave like unix utlities. In particular, I want to use them with pipes, e.g.:
grep foo myfile | ./MyTransformation [--args] | cut -f2 | ...
Three aspects make me wonder how to handle I/O:
According to scources like Useless Use of Cat Award, it would be good to support both, reading from stdin and reading from a file (in the beginning of a pipeline). How is this best accomplished? I'm used to using the
<getopt.h>
/<cgetopt>
stuff for parsing arguments. I could see if there is another file argument besides my options and read from it. If not, read from stdin. That would mean that stdin is ignore if an inut file is supplied. Is this desireable?According to this question, C++ synchronizes
cout
andcin
withstdio
and hence does not buffer well. This leads to a huge decrease in performance. A solution is to disable synchronization:cin.sync_with_stdio(false);
. Should a program for use in pipes always disable synchronization withstdio
forcin
andcout
? Or should it avoid usingcin
andcout
and instead use their own form of buffered io?Since
cout
will be used for program output (unless an output file is specified), status messages (verbosity like % done) have to go somewhere else.cerr/stderr
seems like an obvious choince. However, status are no errors.
In summary, I wonder about the io ahndling of such programs in c++. Can cin
and cout
be used despite the problems addressed above? Should I/O be handled differently? For example, reading and writing from/to buffered files wheres stdin and stdout are default files? What would be the recommended way to implement such a behavior?