// Program to create a file (stock) and maintain it. // Assignment-33 // stckfil.cpp, Author - Krishna Kumar Khatri. // Uncomment ONLY the following line if you are using Turbo/Borland compiler. // #define TC #ifdef TC #include #include #else #include #include using namespace std; #endif #include // For getch. const int MAXLEN = 25; class Inventory { int icode; char iname[MAXLEN]; float icost; public: void getdata(); void putdata(); }; void Inventory::getdata() { cout << "Enter item code: "; cin >> icode; cout << "Enter item name: "; cin >> iname; cout << "Also enter cost: "; cin >> icost; } void Inventory::putdata() { cout << "Item code: "; cout << icode << endl; cout << "Item name: "; cout << iname << endl; cout << "Item cost: "; cout << icost << endl; } int main() { #ifdef TC clrscr(); #endif Inventory invt[MAXLEN / 5]; fstream fn; int n, i; do { cout << "How many items (1-" << MAXLEN / 5 << "): "; cin >> n; } while (n < 1 || n > MAXLEN / 5); fn.open("stock.txt", ios::out | ios::in | ios::trunc); for (i = 0; i < n; i++) { cout << endl << "Enter details for item # " << (i + 1) << endl; invt[i].getdata(); fn.write((char*)&invt[i], sizeof(Inventory)); cout << "Data written to file." << endl; } fn.seekg(0); // Reset the pointer to the BOF (reinitialize). cout << endl << endl << "Reading back from the file." << endl << endl; for (i = 0; i < n; i++) { cout << endl << "Item details for item # " << (i + 1) << endl; fn.read((char*)&invt[i], sizeof(Inventory)); invt[i].putdata(); } cout << endl << endl << "Program over. Press any key to exit..."; getch(); return 0; // Successful termination. }