Issue
I recently learnt that to read properly from a text file we use
while(file>>var1>>var2){
//do stuff with data
}
instead of
while(file){
file>>var1>>var2;
//do stuff with data
}
because the latter performs one extra read even after last data item is read and on the next read it is able to read the eof
, so if we have something like std::vector<CLASSNAME>CLASSVECTOR
, we end up having one extra entry in the vector, while if we use the first method it reads only till the last record.
My question is if how do I read till the last record in case of a binary file? So if I have something like:
class class1 {
int a;
class2 obj2;
class3 obj3;
public:
void write_ binary(std::ofstream file) const;
void read_file(std::ifstream file);
//rest of class definition
};
And I write this class like so :
void class1::write_ binary(std::ofstream file) const {
file.write(reinterpret_cast<const char*>(&a),sizeof(a));
obj2.write_binary(file); //this writes the data in the same way using
reinterpret_cast to ofstream file
obj3.write_binary(file); //this writes the data in the same way using
reinterpret_cast to ofstream file
}
And also if I read the file like so :
void class1::read_file(std::ifstream file) {
file.read(reinterpret_cast<char*>(&a),sizeof(a));
obj2.read_binary(file); //this reads data for obj2 in the same way using
read() and reinterpret_cast
obj3.read_binary(file); //this reads data for obj3 in the same way using read() and reinterpret_cast
}
And if I want to store this data in a vector like so:
class1 obj1;
std::vector<class1>records;
while(file)
{
obj1.read_binary(file);
records.push_back(obj1);
//reset obj1 to initial state
}
I end up getting an extra record in vector records
. I cannot use while(file>>obj1)
since I want to use >>
for cin
.
Please explain how do I read from binary file without reading an extra record.
Solution
It's the same as your text example, the test on the file
must be after the read not before.
for (;;)
{
obj1.read_binary(file);
if (!file) // did the previous read fail?
break; // if so quit the loop
records.push_back(obj1);
}
Answered By - john Answer Checked By - David Goodson (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.