0

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;
}
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
Decky G
  • 29
  • 4
  • 2
    I think you need to [read more about the open mode](https://en.cppreference.com/w/cpp/io/ios_base/openmode). The `ios::ate` flag is wrong. You should also make sure that the `read` operation was successful, and use only the number of bytes that was actually read. Lastly, `buffer` will decay to a pointer of its first element automatically, no cast is needed. – Some programmer dude Jul 11 '18 at 08:29
  • @Someprogrammerdude Why do you write answers as comments? – Maxim Egorushkin Jul 11 '18 at 09:21
  • `read()` returns a count. You are ignoring it. So you are subsequently processing junk. – user207421 Jul 11 '18 at 09:41
  • Why the cast?.. – Paul Sanders Jul 11 '18 at 16:48

0 Answers0