/* Filename: readtext.cpp Author: Br. David Carlson Date: February 23, 1998 Modified: July 4, 1998 Modifed: July 16, 2000 to use modern headers. This program reads a text file (named parts.txt) of parts data, displaying the info on the screen. The data for each part consists of an ID number, number in stock, price, and description, each on a new line of the file. Warning: this simple program does not contain anything to pause the scrolling of the output on the screen. */ #include // needed for files #include "parts.h" // needed for PartType const int MaxString = DescripMax; 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: fs A text file stream already opened for input. Task: To read parts data from fs, writing it onto the screen. Return: fs The modified file stream. */ void ReadFile(fstream & fs) { PartType Part; // Read the first line of the file: fs >> Part.ID; while (! fs.fail()) { // Read the rest of the data on this part: fs >> Part.NumInStock; fs >> Part.Price; fs.get(); // get the newline at the end of the price MyGetLine(fs, Part.Descrip, DescripMax); // Write data from Part onto the screen: cout << "ID: " << Part.ID << endl; cout << "Number in stock: " << Part.NumInStock << endl; cout << "Price: " << Part.Price << endl; cout << Part.Descrip << endl << endl; // Read the next ID from the file: fs >> Part.ID; } } int main(void) { fstream PartFile; PartFile.open("parts.txt", ios::in); if (PartFile.fail()) { cerr << "Could not open file parts.txt" << endl; exit(1); } ReadFile(PartFile); PartFile.close(); return 0; }