Code /* fileio3.cpp David Klick CIS 250 2017-10-06 demonstration of random access file I/O */ #include #include using std::cout; using std::endl; using std::ifstream; using std::ofstream; using std::ios; // this struct defines what the record is in the file struct recType { int n; float x; }; int main(void) { int i; recType rec; rec.x = 0.0f; // open output file as binary ofstream ofile("testfileio3.bin", ios::binary); if (!ofile) { cout << "Error: couldn't open output file" << endl; return 1; } // whole record is written at once to disk for (i=1; i<10; i++) { rec.n = i; ofile.write(reinterpret_cast(&rec), sizeof(rec)); rec.x += 25; } ofile.close(); // open file for input as binary ifstream ifile("testfileio3.bin", ios::binary); if (!ifile) { cout << "Error: couldn't open input file" << endl; return 2; } // find out how many records are in the file ifile.seekg(0L, ios::end); long numrecs = ifile.tellg() / sizeof(rec); // don't forget to get back to start of file ifile.seekg(0L, ios::beg); // read data in record-size chunks for (i=0; i(&rec), sizeof(rec)); cout << rec.n << ", " << rec.x << endl; } ifile.close(); return 0; }