我想将具有浮点值的大型文本文件的大小缩小到二进制 .dat 文件中,所以我使用了(在 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();
然后,我想将之前创建的二进制文件中的所有浮点值读取到浮点值数组中。但是当我尝试从这个文件中读取时,我在最后一行代码(读取过程)出现异常:
// 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));
我究竟做错了什么?