I'm working on a project where I need to read a binary file and then operate on the data(count how many times 3 appears). My approach was to use read() to store data into a char buffer. Then operate on the buffer. My biggest issue is using read() correctly, I don't believe it is storing any data into char buffer. char buffer remains empty after read() is called.
// 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;
}