I have tried using fstream
and although apparently compiled, the program crash.
Please tell me what is wrong in above code and what should I do to correct it
I want to recover all elements of miperro5[]
from the binary file into a new array miperro6[]
. As might fix it?
#include <stdio.h>
#include <iostream>
#include <Perro.hpp>
#include <fstream>
using std::cout;
using std::endl;
int main(int argc, char **argv)
{
Perro miperro5[5];
Perro miperro6[5];
miperro5[2].nombre = "lucky";
std::ofstream myfile;
myfile.open("example.bin", std::ios::out | std::ios::app | std::ios::binary);
for (int i = 0; i < 5; i++){
myfile.write(reinterpret_cast<char *>(&miperro5[i]), sizeof(Perro));
}
myfile.close();
std::ifstream myfile2;
myfile2.open("example.bin", std::ios::in | std::ios::binary);
for (int j = 0; j < 5; j++){
myfile2.read(reinterpret_cast<char *>(&miperro6[j]), sizeof(Perro));
}
myfile2.close();
for (int z = 0; z < 5; z++){
cout << miperro6[z].nombre << endl;
}
std::cin.get();
return 0;
}
This is Perro.hpp
#ifndef PERRO_HPP
#define PERRO_HPP
#include <string>
class Perro
{
public:
Perro();
~Perro();
void ladrar();
void comer();
std::string nombre;
int edad;
int arra[2];
};
#endif // PERRO_HPP