///////////////////////////////////////////////////////////////////////// // fileio.cpp - demonstrate basic file reading and writing // and command line argument handling // // Jim Fawcett, ELE591/791 - Intelligent Systems, Summer 2000 // ///////////////////////////////////////////////////////////////////////// // Demo Program: Reads first few lines of a file as directed by // command line inputs // // Expects a command line of the form: // /17 file1.txt file2.cpp *.h ... // // Demonstrates basic I/O, file I/O, and in memory I/O ///////////////////////////////////////////////////////////////////////// #include // string stream module #include // file stream module #include // basic I/O module #include // manipulators module #include // standard strings module using namespace std; //----< show command line arguments >-------------------------- void displayCommandLine(int argc, char *argv[],ostream &out) { int i; // first argument is name of executing image out << "\n command line arguments are:\n " << argv[0] << "\n "; // arguments to the executing image for(i=1; i--- bool isCommand(const char *s) { if(s[0] == '/' || s[0] == '-') return true; return false; } //----< does this string contain a wild card? >---------------- // // uses standard string find() member function bool isUnexpandedArgument(const string &s) { if(s.find("*") < s.size()) return true; if(s.find("?") < s.size()) return true; return false; } // //----< extract integer value after '/' or '-' >--------------- int getCommand(const char *s) { istringstream temp(&s[1]); int value; temp >> value; // convert string to integer if(temp.good()) // succeeded ? return value; if(temp.eof()) // succeeded and exhausted string return value; return 0; // could not read integer } //----< display first maxLines of file text >------------------ // // uses global function getline(istream, string) // defined in string module void processFile(istream &in, ostream &out, int maxLines) { string line; int lineCount = 0; while(in.good() && lineCount < maxLines) { getline(in,line); out << "\n" << setw(4) << ++lineCount << " " << line; } out << "\n\n"; } //----< display file tops >------------------------------------ // // Accept directions from command line or user, then display // file data accordingly. void main(int argc, char *argv[]) { cout << "\n Display Top Few Lines of File " << "\n ===============================\n"; displayCommandLine(argc,argv,cout); int maxLines = 10; ifstream in; if(argc == 1) { // no command line arguments string s; cout << "\n please enter the name of a data file to read: "; cin >> s; in.open(s.c_str()); processFile(in,cout,maxLines); in.close(); } // else { // found command line arguments int i; for(i=1; i