<> wrote:
> I've written a little command line utility. So far it just reads from
> stdin using cin and outputs to stdout using cout. I would like to
> generalize it some by being able to specify input and output files on
> the command line while retaining the ability to use stdin and stdout
> if no files are specified on the command line. My thinking is that I
> need to replace all instances of cin and cout with some generic names
> like 'infile' and 'outfile' and then set them to point to either (cin
> | cout) or the file specified on the command line after parsing the
> command line, but I can't seem to find the correct way to code this.
> Is this the correct approach and, if so, could someone post a hint and/
> or sample code? Thanks!
Sure. Here is some example code showing how such a infile could be coded:
int main(int argc, char** argv)
{
bool usecin;
std::string infilename;
// fill in those variables
std::ifstream ifs;
if (!usecin) ifs.open(infilename.c_str());
std::istream& infile = (usecin)?(std::cin):ifs;
//later:
int i;
infile >> i;
return i;
}
I'm sure you can figure out how to add the outfile variable to the above.
Notice the fact that infile is a reference. That is the easiest way to just
make this work.
Unfortunately, this particular solution form could be problematic if
additional user-defined functions are used, as that would nesesiatate
additional parameters to the functions. (namely a "std::istream& infile"
parameter and a "std:

stream& outfile" parameter. )
I've seen solution that involved replacing the streambuf of std::cin and
std::cout, but those don't seem very clean to me.