views:

181

answers:

3

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?

+3  A: 
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));
Magnus Hoff
+3  A: 

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.

Manuel
you're right, but if I write fstream.read(static_cast<char*>(pBuff), tokensCount * sizeof(float));it still does not compile...
melculetz
Sorry, I only tested this with a char * pBuff, but it doesn't work when pBuff is of any other type. Is there any way that I can return the rep I've gained from these upvotes?
Manuel
@Manuel: Don't worry. It is good advice to use the C++-style casts anyway, even though `reinterpret_cast` might be more appropriate here.
Magnus Hoff
+3  A: 

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));
}
anon