我想收缩与浮点值大的文本文件转换成一个二进制.dat文件的大小,所以就用(在C++):二进制.dat文件问题
// 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();
然后,我想从rpeviously创建的二进制文件中读取所有的浮点值到一个浮点值数组中。 但是,当我尝试从这个文件中读取我在最后一行代码(阅读过程中)得到一个异常:
// 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));
我在做什么错?
你是对的,但如果我写 fstream.read(的static_cast(PBUFF),tokensCount *的sizeof(浮动)); 它仍然不能编译... –
melculetz
2010-02-09 12:27:28
对不起,我只用char * pBuff对其进行了测试,但当pBuff是任何其他类型时,它不起作用。有什么方法可以让我从这些upvotes中获得的代表回复? – Manuel 2010-02-09 12:53:30
别担心。尽管'reinterpret_cast'在这里可能更适合,不管怎么说,使用C++风格的类型转换都是很好的建议。 – 2010-02-10 11:35:45