/* Example echoInt3.cpp shinnerl@ucla.edu 2/5/2002 ----------------------------------------------------- Echo all ASCII values of a file's contents to either the screen, or to a user-specified file, if requested by an optional command-line argument. As before, to avoid an excess of conditional blocks testing where the output should go, we use a pointer to an output stream. We can set this pointer inside a local function, rather than in main(), if we pass the pointer to the function *by reference.* See related example echoInt2.cpp for additional explanation. */ #include #include #include #include #include #include using namespace std; const int FIELDWIDTH = 10; const int INTSPERLINE = 6; const string sep = " "; void getCommandLine( int argc, char* argv[], ifstream& is, ofstream& os, ostream*& osPtr ){ if (argc > 1) cout << "The input file name is " << argv[1] << "." << endl; else{ cout << "The input file name must be provided as a command-line " << "argument.\n" << "Syntax: echoInt3 [output file (optional)] " << endl << endl; exit(-1); } // Open the file and attach the ifstream to it. is.open( argv[1] ); // ifstream::open() requires a C-style string. if (!is){ cout << "File not found!" << endl; exit(1); } if (argc > 2){ os.open( argv[2] ); assert( os ); osPtr = &os; cout << "The output file name is " << argv[2] << ".\n" << endl; } } int main(int argc, char* argv[]){ ifstream userIfs; ostream* osPtr = &cout; // Output to the screen by default. ofstream userOfs; getCommandLine( argc, argv, userIfs, userOfs, osPtr ); // Print the ASCII values of the input stream's contents // to the requested output stream. Using a pointer avoids // the need for repeated checks of which ostream is wanted. char ch; int i = 0; *osPtr << "The ASCII values of the characters in this input file are " << "\ndisplayed below, " << INTSPERLINE << " values per line: " << endl; while (userIfs.get(ch)){ *osPtr << setw(FIELDWIDTH) << int(ch) << sep; if (!(++i%INTSPERLINE)) *osPtr << endl; } *osPtr << "The number of characters in this input stream is " << i << ". " << endl << endl; return 0; } /* Sample I/O for file "data.dat" containing one line: abcde: whale.44> echoInt3 data.dat The input file name is data.dat. The ASCII values of the characters in this input stream are displayed below, 6 values per line: 97 98 99 100 101 10 The number of characters in this input stream is 6. whale.45> echoInt3 The input file name must be provided as a command-line argument. Syntax: echoInt3 [output file (optional)] whale.46> echoInt3 data.dat dataOut.dat The input file name is data.dat. The output file name is dataOut.dat. whale.47> cat dataOut.dat The ASCII values of the characters in this input stream are displayed below, 6 values per line: 97 98 99 100 101 10 The number of characters in this input stream is 6. whale.48> */