Leila Saeedy
Leila Saeedy

Reputation: 39

how can i write an array of structures to a binary file and read it again?

I'm writing an array af structures(factor is a structure) to a binary file like this:

factor factors[100];

ofstream fa("Desktop:\\fa.dat", ios::out | ios::binary);
fa.write(reinterpret_cast<const char*>(&factors),sizeof(factors));

fa.close();

and I run the program and save 5 records in it.in another file, I want to read the structures so I wrote this:

    int i=0;
ifstream a("Desktop:\\fa.dat", ios::in | ios::binary);

factor undelivered_Factors[100];

    while(a && !a.eof()){
        a.read(reinterpret_cast<char*>(&undelivered_Factors),sizeof(undelivered_Factors));
        cout<<undelivered_Factors[i].ID<<"\t"<<undelivered_Factors[i].total_price<<endl;
        i++;
    }
    a.close();

but after reading and printing the saved factors it inly reads and shows the firs 2 of them in the array.why?what should i do?

Upvotes: 1

Views: 1221

Answers (2)

Hemant Gangwar
Hemant Gangwar

Reputation: 2272

You are doing complete read in the single call so your loop runs only one time hence it will output only first struct value. Change your while loop like this:

if(a)
{
   a.read(reinterpret_cast<char*>(&undelivered_Factors),sizeof(undelivered_Factors));
}
for(int i=0; i<100; ++i)
{
   cout<<undelivered_Factors[i].ID<<"\t"<<undelivered_Factors[i].total_price<<endl;
}

Upvotes: 0

Swift - Friday Pie
Swift - Friday Pie

Reputation: 14688

Second parameter of ofstream::write and ::read is size of written memory in bytes (aka 'char' in C\C++), which is right - you're writing entire array at once. In reading procedure you had mixed up an per element and array processing. You expect to read whole array, then you print one value, then you read another 100 of records which you do not have in file, I presume. also eof() happens only when you attempt to read and it failed. If you stand on end of file,eof() isn't triggered, that's why you get two records printed.

Upvotes: 1

Related Questions