/* Filename: makepart.cpp Author: Br. David Carlson Date: February 23, 1998 Revised: July 4, 1998 Revised: July 16, 2000 to use modern headers. This program creates a binary file of parts records. The data for each record consists of an ID number, number in stock, price, and description, and is read from the keyboard and written to this binary file, called parts.dat. */ #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 binary file stream already opened for output. Task: To read parts data from the user, writing each record of accumulated data to fs. Return: fs The modified file stream. */ void WriteToFile(fstream & fs) { int RecordSize, Number; PartType Part; RecordSize = sizeof(Part); cout << "Enter a part number (or 0 to exit): "; cin >> Number; while (Number != 0) { // Put data into the Part record: Part.ID = Number; cout << "Enter number in stock: "; cin >> Part.NumInStock; cout << "Enter price: "; cin >> Part.Price; cin.get(); // input newline at end of price cout << "Enter description: "; MyGetLine(cin, Part.Descrip, DescripMax); // Write the Part record to the binary file: fs.write(reinterpret_cast (&Part), RecordSize); cout << "Enter a part number (or 0 to exit): "; cin >> Number; } } int main(void) { fstream PartFile; PartFile.open("parts.dat", ios::out | ios::binary); if (PartFile.fail()) { cerr << "Could not create file parts.dat" << endl; exit(1); } WriteToFile(PartFile); PartFile.close(); return 0; }