【问题标题】:C++: FStream thinks it has reached EOF of binary fileC ++:FStream认为它已达到二进制文件的EOF
【发布时间】:2016-02-17 17:31:58
【问题描述】:

我正在尝试读取以下格式的二进制文件:

-64 位整数

-3276 32 位浮点数

-(重复最后两行直到 eof)

这是我解释文件的块:

ifstream bbrFile;
ofstream csvFile;

bbrFile.open(inFilename);
csvFile.open(dataFilename);
//yes I did actually check to make sure that the files had opened. 
//I omitted it here for brevity

long long int time;
float point;
while (bbrFile)
{
    bbrFile.read((char*)&time, sizeof(time));
    csvFile << time;
    for (int i = 0; i < 3276; i++) {
                bbrFile.read((char*)&point, sizeof(point));
                csvFile << ',' << point;
    }
    csvFile << "\n";
}

到目前为止,我的代码工作正常,只是它认为在读取大约 53 个浮点数后它已到达文件末尾,然后只输出它读取的最后一个浮点数,直到“for”循环结束。我尝试使用 fread 和 FILE* 而不是 read 和 fstream,得到了相同的结果。我也试过替换

while (bbrFile)

while (!bbrFile.eof())

无济于事。

由于二进制文件大约有 12 兆字节,我有点不知道为什么它在这里停止读取。

【问题讨论】:

  • 什么是trace?这在这里似乎很重要。
  • 这是我从自己的代码中复制时犯的错误。 trace 应改为 point

标签: c++ binary fstream eof


【解决方案1】:

要将文件作为二进制文件读取,应在文件模式中添加binary

bbrFile.open(inFilename, ios::binary);

否则它将被读取为文本文件,并且某些代码可能被解释为文件结束标记。

【讨论】:

  • 完美运行。感谢您的帮助。
猜你喜欢
  • 2012-12-27
  • 2019-04-24
  • 1970-01-01
  • 1970-01-01
  • 2016-02-14
  • 2016-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多