Below is the code for reading a struct that was stored in a binary file.
Problem is while reading from file I get the name without first character and age is always equal to zero which it should not be.
Please explain what's wrong with the code?
I don't see why do you need to use seekg. You read data from file sequentially anyway. I'd recommend replacing lines 57-75 with
1 2 3 4 5 6 7 8 9 10
while(inFile.read((char*)&a,sizeof(struct abc)))
{
if(age == a.age)
{
cout<<"found at "<<counter<<endl;
cout<<"name is "<<a.name<<endl;
cout<<"age is "<<a.age;
break;
}
}
Or if you really want to use seek - then you seek at wrong location. You need to offset your read position by sizeof(abc), not by 1. Means that line 66 should look like counter+=sizeof(abc);. Plus in this case you still have flawed logic - if you found a record with the given age you only set the check = 1. On the next iteration of the while loop, the data in object b will be overwritten so your output will be wrong. To fix that you need to break the loop as soon as you've found a record with correct age - add a break; after line 64;
By the way, the version of the while loop I proposed can be easily changed for output of all records with the given age - just remove the break statement in line 8.