我正在尝试读取具有以下格式的二进制文件:
-64位整数
-3276 32 位 float
-(重复最后两行直到eof)
这是我解释文件的 block :
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 个 float 后到达了文件末尾,然后只输出它读取的最后一个 float ,直到“for”循环结束。我试过使用 fread 和 FILE* 而不是 read 和 fstream,并得到了相同的结果。我也试过更换
while (bbrFile)
与
while (!bbrFile.eof())
没用。
由于二进制文件大约有 12 兆字节,我有点不明白为什么它会在这里停止读取。
最佳答案
要将文件作为二进制文件读取,您应该将 binary
添加到文件模式:
bbrFile.open(inFilename, ios::binary);
否则它将被读取为文本文件,并且某些代码可能被解释为文件结束标记。
关于C++: FStream 认为它已经到达二进制文件的 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35463708/