Reading a file into vectors
Jan 26, 2014 at 10:16pm UTC
My program writes a vector to a file in binary. I want to erase the vector, then read the file to repopulate the vector then display.
Basically I want to erase the RAM memory and be able to use the file as memory. This is my current code but it is not reading the file correctly. I have checked the file to see that the writing part is working.
Any ideas?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
void read_from_file(vector<Info> &vector)
{
fstream file;
file.open("info.dat" , ios::binary | ios::in);
if (file.fail())
{
cout<<"\n FILE DOES NOT EXIST \n" ;
system("pause" );
}
if (file.good())
{
for (int count = 0;count < vector.size(); count++)
{
file.read(reinterpret_cast <char *>(&vector[count]),sizeof (vector[count]));
}
for (int count = 0; count < vector.size(); count++)
{
cout << endl << (count) << ". NAME: " << vector[count].name << endl;
cout << (count) << ". AGE: " << vector[count].age << endl;
}
}
cout<<"\nINFORMATION READ FROM THE FILE\n" ;
file.close();
}
Jan 26, 2014 at 10:57pm UTC
Can you show us the definition of Info ? Only POD structures can be serialized this way.
Jan 26, 2014 at 11:08pm UTC
I would post the entire program but its huge. This is the structure with Info.
1 2 3 4 5 6 7 8
const int name_size = 20;
struct Info{
char name[name_size];
int age;
};
In the main function I declare the vector
1 2 3 4 5 6 7
int main()
{
vector<Info> vector, vector1;
......
Last edited on Jan 26, 2014 at 11:25pm UTC
Topic archived. No new replies allowed.