This question already has an answer here:
I wrote a code to save stl::vector into a binary file. In the following example, I stored 4 floats and obviously the size of the file is 16 bytes. But when I read them it reads 5 floats! Why??!?
#include <vector>
#include <fstream>
int main( int argc, const char** argv )
{
std::vector<float> fv1;
std::vector<float> fv2;
fv1.push_back(1.54);
fv1.push_back(2.566);
fv1.push_back(2.234522);
fv1.push_back(2.2245);
std::ofstream out2("test.bin",std::ios_base::binary);
if(out2.good())
{
out2.write((char *)&fv1[0],sizeof(float)*fv1.size());
out2.close();
}
std::ifstream in2("test.bin",std::ios_base::binary);
while(!in2.eof())
{
float ftmp;
in2.read((char *)&ftmp,sizeof(float));
fv2.push_back(ftmp);
std::cout << "Reading floating point number: " << std::fixed << ftmp << std::endl;
}
std::cout << "vector size: " << fv2.size() << std::endl;
for(auto i:fv2)
std::cout<<"fv2:"<<i<<std::endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire