The iostream_withassign class lets you associate a stream object with one of the predefined streams cin, cout, cerr, and clog. You can do this, for example, to write programs that accept input from a file if a file is specified, or from standard input if no file is specified.
The following program is a simple filter that reads input from a file into a character array, and writes the array out to a second file. If only one file is specified on the command line, the output is sent to standard output. If no file is specified, the input is taken from standard input. The program uses the iostream_withassign assignment operator to assign an ifstream or ofstream object to one of the predefined streams.
// Generic I/O Stream filter, invoked as follows: // filter [infile [outfile] ]
#include <iostream.h> #include <fstream.h>
void main(int argc, char* argv[]) {
ifstream* infile;
ofstream* outfile;
char inputline[4096]; // used to read input lines
int sinl=sizeof(inputline); // used by getline() function
if (argc>1) { // if at least an input file was specified
infile = new ifstream(argv[1]); // try opening it
if (infile->good()) // if it opens successfully
cin = *infile; // assign input file to cin
if (argc>2) { // if an output file was also specified
outfile = new ofstream(argv[2]); // try opening it
if (outfile->good()) // if it opens successfully
cout = *outfile; // assign output file to cout
}
}
cin.getline(inputline,
sizeof(inputline),'\n'); // get first line
while (cin.good()) { // while input is good
//
// Insert any line-by-line filtering here
//
cout << inputline << endl; // write line
cin.getline(inputline,sinl,'\n'); // get next line (sinl specifies
} // max chars to read)
if (argc>1) { // if input file was used
infile->close(); // then close it
if (argc>2) { // if output file was used
outfile->close(); // then close it
}
}
}
You can use this example as a starting point for writing a text filter that scans a file line by line, makes changes to certain lines, and writes all lines to an output file.