0

I am not able to append the data on bin file. It always truncated to 0 and start writing on file please suggest how to append data on file i have tried everything

I have tried to read and write the person identity data using class and fstream and iostream library

Please suggest that should I use fstream library for file handling or C stdio.h library

    class identity
    {
        int age;
        char name[20];
    public:
        identity()
        {}
        void getdata()  // input the data
        {
            cout<<"enter your name :";
            cin>>name;
            cout<<"\nenter your age :";
            cin>>age;
        }
        void putdata()  //display the data
        {
         cout<<"Name :"<<name<<endl;
         cout<<"age :"<<age<<endl;
        }
    };

    int main()
    { 
        int i;
        identity i1[2];
        ofstream fobj;
        //opening of Irecord file
        fobj.open("Irecord.dat",ios::out|ios::app|ios::binary);

        for(i=0;i<2;i++)
        {
           i1[i].getdata();
           fobj.write((char*)&i1[i],sizeof(i1[i]));      
        }

        ifstream fin("Irecord",ios::in|ios::binary);
        fin.seekg(0,ios::beg);
        for(i=0;i<20;i++)
        { 
          fin.read((char*)&i1[i],sizeof(i1[i]));
          i1[i].putdata();
        }
        cout<<endl;
        fobj.close();

        return 0;
    }

data doesn't append on file it get truncated to 0.

harper
  • 13,345
  • 8
  • 56
  • 105

1 Answers1

0

Change : ifstream fin("Irecord.dat",ios::in|ios::binary);

You are trying to open a file which is not there.

Put this below check right after you open the file to find out whether the open call was successful or not.

if (!fin.is_open()) 
    {
        cout << "File opening failed";
    } 
user3152801
  • 81
  • 1
  • 5