This example is also available here: fileio2.cpp
#include <fstream>
#include <iostream>
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<char *>(&n), sizeof(n));
ofile.write(reinterpret_cast<char *>(&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<char *>(&n), sizeof(n));
ifile.read(reinterpret_cast<char *>(&x), sizeof(x));
while (ifile) {
cout << n << ", " << x << endl;
ifile.read(reinterpret_cast<char *>(&n), sizeof(n));
ifile.read(reinterpret_cast<char *>(&x), sizeof(x));
}
ifile.close();
return 0;
}