//Listing 14.06 Writing an array of Structs to a File
#include <fstream>
#include <iostream>
#include <cassert> // assert()
using namespace std;
typedef struct {
int x;
int y;
} Vector;
void ingresar(ofstream* p_out, Vector* ptr, int cap);
void mostrar(ifstream* p_in, int cap);
int main() {
char fileName[80] = "";
int n = 0;
Vector* ptr = nullptr;
cout << "Please enter the file name: ";
cin >> fileName;
ofstream fout(fileName, ios::binary); // establish connection,
assert( fout.is_open() ); // and check for success
cout << "ingrese la cantidad de vectores a escribir\t:\t"; cin >> n;
ptr = new Vector[n];
ingresar(&fout, ptr, n);
delete [] ptr;
fout.close();
ifstream fin(fileName, ios::binary); // establish connection,
assert( fin.is_open() ); // and check for success
mostrar(&fin,n);
fin.close();
return 0;
}
void ingresar(ofstream* p_out, Vector* ptr, int cap) {
for (int j = 0; j < cap; ++j) {
ptr[j].x = rand()%4;
ptr[j].y = rand()%4;
p_out[0].write(reinterpret_cast<char*>(ptr + j), sizeof ptr[j]);
}
}
void mostrar(ifstream* p_in, int cap) {
Vector v2 = {0,0};
for (int j = 0; j < cap; ++j) {
p_in[0].read(reinterpret_cast<char*>(&v2), sizeof v2);
cout << "v2.x\t:\t" << v2.x << endl;
cout << "v2.y\t:\t" << v2.y << endl << endl;
}
}