1

我想将具有浮点值的大型文本文件的大小缩小到二进制 .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));

我究竟做错了什么?

4

3 回答 3

5
float* pBuff = new float[tokensCount];
fstream.read((char*)&pBuff, tokensCount * sizeof(float));

您正在读取pBuff变量,而不是它指向的缓冲区。你的意思是:

fstream.read((char*)pBuff, tokensCount * sizeof(float));
于 2010-02-09T10:39:33.563 回答
5

请注意:

while(!fin.eof())
{
    fin >> val;     
    out.write((char *)&val,sizeof(float));
}

不是读取文件的正确方法——它最后会读取一个垃圾值。您几乎不应该使用该eof()功能,并且您应该始终检查文件读取是否有效。正确的代码是:

while( fin >> val )
{
    out.write((char *)&val,sizeof(float));
}
于 2010-02-09T10:49:28.813 回答
4

Magnus 的回答是正确的,应该可以解决您的问题。我只会补充一点,如果您按照大师所说的那样做并且没有使用邪恶的 C 风格演员表,那么您一开始就不会遇到问题。如果您将最后一行更改为:

fstream.read(static_cast<char*>(&pBuff), tokensCount * sizeof(float));

那么您的程序将无法编译,错误消息将引导您找到解决方案。

编辑:如果 pBuff 是指向除 char 以外的任何类型的指针,我的解决方案将不起作用。所以在OP的情况下没有用。

于 2010-02-09T10:47:43.840 回答