/* fileio2.cpp David Klick CIS 250 1/31/05 demonstration of binary file I/O */ #include #include using std::cout; using std::endl; using std::ifstream; using std::ofstream; using std::ios; int main(void) { int n; float x = 0.0f; // specify binary when opening file ofstream ofile("testfileio2.txt", ios::binary); if (!ofile) { cout << "Error: couldn't open output file" << endl; return 1; } // use write function to write binary data for (n=1; n<10; n++, x+=25) { ofile.write(reinterpret_cast(&n), sizeof(n)); ofile.write(reinterpret_cast(&x), sizeof(x)); } ofile.close(); // specify binary when opening file ifstream ifile("testfileio2.txt", ios::binary); if (!ifile) { cout << "Error: couldn't open input file" << endl; return 2; } // use priming read and loop to read all records ifile.read(reinterpret_cast(&n), sizeof(n)); ifile.read(reinterpret_cast(&x), sizeof(x)); while (ifile) { cout << n << ", " << x << endl; ifile.read(reinterpret_cast(&n), sizeof(n)); ifile.read(reinterpret_cast(&x), sizeof(x)); } ifile.close(); return 0; }