/* Filename: readtext.cpp Author: Br. David Carlson Date: February 1, 1998 Revised: June 9, 1998 Revised: July 12, 2000 to use modern headers. This program prompts the user for the name of a text file to read. It then displays the file's contents on the screen. */ #include #include // needed for files using namespace std; const int MaxString = 120; typedef char StringType[MaxString]; /* Given: InStream An input file stream already open for reading. StringMax The maximum number of characters that can be put into String, including the NULL that marks the end of the string. Task: To read up to StringMax - 1 characters from InStream, storing them in String, but stopping if a newline is read or end of file or an error condition is reached. Return: String The string just read, with a NULL appended to mark the end of the string. If a newline was read, it is not stored in String. The number of characters read into String (not counting the NULL) is returned in the function name. */ int MyGetLine(istream & InStream, char * String, int StringMax) { char Ch; int Count, Last; Count = 0; Last = StringMax - 1; Ch = InStream.get(); while ((Ch != '\n') && (! InStream.fail())) { if (Count < Last) String[Count++] = Ch; Ch = InStream.get(); } String[Count] = NULL; return Count; } /* Given: InFile A file stream already opened for input. Assumes: That InFile is associated with a text file. Task: To display on screen the contents of the file. Return: InFile The modified file stream. */ void DisplayFile(fstream & InFile) { StringType Line; int CharCount; int LineCount = 0; CharCount = MyGetLine(InFile, Line, MaxString); while ((CharCount > 0) || (! InFile.fail())) { cout << Line << endl; LineCount++; if (LineCount == 22) { LineCount = 0; cout << " Press ENTER to go on..."; cin.get(); } CharCount = MyGetLine(InFile, Line, MaxString); } if (LineCount != 0) { cout << " Press ENTER to go on..."; cin.get(); } } int main(void) { StringType FileName; fstream InFile; cout << "Enter the name of the text file to be read: "; MyGetLine(cin, FileName, MaxString); InFile.open(FileName, ios::in); if (InFile.fail()) { cerr << "Could not open file " << FileName << endl; exit(1); } DisplayFile(InFile); InFile.close(); return 0; }