1

First time execution is success without any error but when it creates Data.bin I get some error when I use fread. Sorry I don't know how to ask it so please look at the program. I commented the error making statement.

#include<iostream>
#include<vector>
using namespace std;

typedef struct myStuff
{
    int cdno;
    string content,des;
}MS;

int main()
{
    vector<MS> data;
    int i=0;
    string in;
    FILE *fr=NULL,*fw=NULL;
    fr=fopen("Data.bin","rb");


    //----------------------------------------------------------------------
    if(fr!=NULL)
    {
        do
        {
            data.resize(++i);
        }while( fread(&data[i-1],sizeof(MS),1,fr) ); //ERROR
        fclose(fr);
    }
    else
        data.resize(++i);

    //----------------------------------------------------------------------
    while(1)
    {
        cout<<"Enter x to exit or c to continue updating data: ";
        cin>>in;
        if(in=="x"||in=="X")
        {
            fw=fopen("Data.bin","wb");
            fwrite(&data[i],sizeof(MS),i,fw);
            fclose(fw);
            exit(0);
        }
        else if(in=="c"||in=="C")
        {
            cout<<"Enter CD no: ";
            cin>>data[i-1].cdno;
            cout<<"Enter Contents: ";
            cin>>data[i-1].content;
            cout<<"Enter Description: ";
            cin>>data[i-1].des;
            data.resize(++i);
        }
        else
            cout<<"Try Again..."<<endl;
    }
}

1 Answer 1

1

you shouldn't use sizeof(string) or sizeof a structure that contains a string, that's meaningless, it just gives you the compile time (static) size of the class string. you should instead use string.size() which returns the dynamic size of the string.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.