c++ file handling - class objects
<p>The following code read 3 obj and write them into a file.
however im unable to retrieve objects properly using the below code.
data is duplicated and is not in order</p>

<p>plz help</p>

<p>old code :</p>

<pre><code>#include&lt;fstream.h&gt;
#include&lt;conio.h&gt;

class mail
{
  public:
    char un[25];             // user name
    char pd[25];             // passsword

    void reg(int);

} obj[5];

void mail::reg(int k)
{
  int i;
  i=k;

  clrscr();
  cout&lt;&lt;"Enter user name ( enter unique name )\n";
  cin&gt;&gt;un;


  cout&lt;&lt;"Enter password\n";
  cin&gt;&gt;pd;

  ofstream filout;
  filout.open("email",ios::app||ios::binary);
  if(!filout)
  {
    cout&lt;&lt;"cannot open file\n";
  }
  else
  {
    cout&lt;&lt;"\n "&lt;&lt;i;
    filout.write((char *)&amp;obj[i],sizeof(mail));
    filout.close();
  }

  cout&lt;&lt;"You are now registered. \n";
  getch();

}        // end of sign up or register func

void main()
{

  int t;
  clrscr();
  obj[0].reg(0);
  obj[1].reg(1);
  obj[2].reg(2);

  mail obj2;

  ifstream filein;
  filein.open("email",ios::in||ios::binary);
  if(!filein)
  {
    cout&lt;&lt;"Unable to open file to read\n";
  }
  else
  {
    while(!filein.eof())
    {

      filein.read((char *)&amp;obj2,sizeof(obj2));

      cout&lt;&lt;"username "&lt;&lt;obj2.un&lt;&lt;" passwword "&lt;&lt;obj2.pd&lt;&lt;"\n";
    }
    filein.close();
  }
  getch();

}
</code></pre>

<p>Also please tell me how to put code into stackoverflow. Manually putting 4 spaces after copy pasting is very tiresome</p>

<p>new code after making changes :</p>

<pre><code>#include&lt;fstream.h&gt;
#include&lt;conio.h&gt;

struct mail
{
    char un[25];             // user name
    char pd[25];             // passsword
    void reg(int);
} obj[5];

void mail::reg(int k)
{
    int i=k;
    clrscr();
    cout&lt;&lt;"Enter user name ( enter unique name )\n";
    cin&gt;&gt;un;
    cout&lt;&lt;"Enter password\n";
    cin&gt;&gt;pd;

    ofstream filout;
    filout.open("email",ios::app|ios::binary);
    if(!filout) {
        cout&lt;&lt;"cannot open file\n";
    } else {
        cout&lt;&lt;"\n "&lt;&lt;i;
        filout.write((char *)&amp;obj[i],sizeof(mail));
        filout.close();
    }

    cout&lt;&lt;"You are now registered. \n";
    getch();

}   // end of sign up or register func

int main()
{
    int t;
    clrscr();
    obj[0].reg(0);
    obj[1].reg(1);
    obj[2].reg(2);

    mail obj2;

    ifstream filein;
    filein.open("email",ios::in|ios::binary);
    if(!filein) {
        cout&lt;&lt;"Unable to open file to read\n";
    } else {
        while(filein) {
            filein.read((char *)&amp;obj2,sizeof(obj2));

            cout&lt;&lt;"username "&lt;&lt;obj2.un&lt;&lt;" passwword "&lt;&lt;obj2.pd&lt;&lt;"\n";
        }
        filein.close();
    }
    getch();
}
</code></pre>

<p>Im still facing problem. I write 3 object. But iam getting 4 output records. Last one is duplicated.   </p>
