title: C++: Read and write classes
body: <pre><code>#include &lt;cstdlib&gt;
  #include &lt;iostream&gt;
  #include &lt;fstream&gt;
  #include &lt;string&gt;
  
  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 &lt;&lt; name &lt;&lt; " " &lt;&lt; surname &lt;&lt; "\n";
      }
  
      void save(PERSON *x){
          ofstream file("test.bin", ios::out | ios::app | ios::binary);
  
  
          if(!file.is_open()){
                  cout &lt;&lt; "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-&gt;set_name("Amon", "Raa");
      person1-&gt;save(oseba1);
  
  
  
  
  
  
  
  
      ifstream file2("test.bin", ios::in | ios::binary);
  
      if(!file2.is_open()){
          cout &lt;&lt; "Error\n";
          return 0;
      }
  
  
      while(!file2.eof()){
          file2.read((char *)person2, sizeof(*person2));
          person2-&gt;output();
      }
  
      file2.close(); 
  
  
      return 0;
  
  
  }
  </code></pre>
  
  <p>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...</p>
  
  <p>but each time I run the program I get printed only the last entered name</p>
  
  <p>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</p>
  
  <p>Please help... I am a complete beginner ;(</p>