#include <cstdlib>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
class PERSON{
string name, surname;
public:
void set_name(string aname, string asurname){
name = aname;
surname = asurname;
};
void read(){
}
void output(){
cout << name << " " << surname << "\n";
}
void save(PERSON *x){
ofstream file("test.bin", ios::out | ios::app | ios::binary);
if(!file.is_open()){
cout << "ERROR\n";
}else{
file.write((char*)x, sizeof(*x));
file.close();
}
}
};
/*
*
*
*
*/
int main(int argc, char** argv) {
PERSON * person1 = new PERSON;
PERSON * person2 = new PERSON;
person1->set_name("Amon", "Raa");
person1->save(oseba1);
ifstream file2("test.bin", ios::in | ios::binary);
if(!file2.is_open()){
cout << "Error\n";
return 0;
}
while(!file2.eof()){
file2.read((char *)person2, sizeof(*person2));
person2->output();
}
file2.close();
return 0;
}
This is my code...what I am doing wrong? What I am trying to do is to save each time a class to the end of the binary file and then read all entries...
but each time I run the program I get printed only the last entered name
so run it first time the file is written correctly and the output is OK then I change the name to something else, lets say John Doe, I get the output of 2times John Doe
Please help... I am a complete beginner ;(