Binary .dat file question in c++
-
19-09-2019 - |
Question
I wanted to shrink the size of a large text file with float values into a binary .dat file, so I used (in c++):
// the text stream
std::ifstream fin(sourceFile);
// the binary output stream
std::ofstream out(destinationFile, std::ios::binary);
float val;
while(!fin.eof())
{
fin >> val;
out.write((char *)&val,sizeof(float));
}
fin.close();
out.close();
Then, I wanted to read all the float values from the rpeviously created binary file into a array of float values. But when I try to read from this file I get an exception at the last line of code (the reading process):
// test read
std::ifstream fstream(destinationFile, std::ios::binary);
__int64 fileSize = 0;
struct __stat64 fileStat;
if(0 == _tstat64(destinationFile, &fileStat))
{
fileSize = fileStat.st_size;
}
//get the number of float tokens in the file
size_t tokensCount = fileSize / sizeof(float);
float* pBuff = new float[tokensCount];
fstream.read((char*)&pBuff, tokensCount * sizeof(float));
What am I doing wrong?
Solution
float* pBuff = new float[tokensCount];
fstream.read((char*)&pBuff, tokensCount * sizeof(float));
You are reading into the pBuff
variable, not the buffer it points to. You mean:
fstream.read((char*)pBuff, tokensCount * sizeof(float));
OTHER TIPS
Note that this:
while(!fin.eof())
{
fin >> val;
out.write((char *)&val,sizeof(float));
}
is not the correct way to read a file - it will read a garbage value at the end. You should almost never use the eof()
function and you should ALWAYS check that a file read worked. Correct code is:
while( fin >> val )
{
out.write((char *)&val,sizeof(float));
}
Magnus' answer is correct and should solve your problem. I will only add that you wouldn't have had a problem in the first place if you had done as the gurus say and not used an evil C-style cast. If you change your last line to this:
fstream.read(static_cast<char*>(&pBuff), tokensCount * sizeof(float));
Then your program would have failed to compile and the error message would have led you to the solution.
EDIT: my solution does not work if pBuff is a pointer to any type other than char. So it's no use in the OP's case.