1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include <iostream>
#include <fstream>
#include <iterator>
using namespace std;
const int size = 10;
void create_file(const char * fname)
{
int numbers[size] = { 53, 59, 61, 67, 71, 73, 79, 83, 89, 97 };
ofstream fout(fname, ios::binary);
fout.write(reinterpret_cast<const char *>(numbers), size * sizeof(int));
}
struct my_int {
int n;
};
istream & operator >> (istream & is, my_int & m)
{
is.read(reinterpret_cast<char *>(&m.n), sizeof m.n);
return is;
}
int main()
{
// First generate a file containing the binary data
create_file("test.bin");
// now attempt to read it back in.
ifstream fin("test.bin", ios::binary);
if (!fin)
{
cout << "file not open\n";
return 1;
}
istream_iterator<my_int> eos;
istream_iterator<my_int> itr(fin);
while (itr != eos)
{
cout << itr->n << '\n';
++itr;
}
}
|