简体   繁体   中英

how to append data on binary file?

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.

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";
    } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM