我在一个项目中,我需要读取一个二进制文件,然后对数据进行操作(计算出现3次的次数)。我的方法是使用read()将数据存储到char缓冲区中。然后在缓冲区上进行操作。我最大的问题是正确使用read(),我不认为它会将任何数据存储到char缓冲区中。调用read()后,char缓冲区保持为空。
// Program reads how many times the integer 3 occurs in a binary file
#include <iostream>
#include <fstream> // needed to use files
using namespace std;
int main()
{
int count = 0;
char buffer[32];
int size = sizeof(buffer) / sizeof(buffer[0]);
// open file "example.bin"
fstream file("example.bin", ios::in | ios::ate | ios::binary);
if(!file)
{
cout << "Error opening file" << endl;
return 0;
}
cout << "opened file" << endl;
// reading the data into memory
file.read(reinterpret_cast<char *>(buffer), sizeof(buffer));
for(int i = 0; i < size; i++)
{
if (buffer[i] == '3')
count++;
}
cout << "There exists " << count << " threes in this file." << endl;
// close file
file.close();
return 0;
}