My objective is to read in data from a binary file and ultimately store the bits in 32bit slices. I have found a few different methods of reading binary in C++ but am not sure which is the best option and my main issue is that when outputting the data after having stored it I am not accessing individual bits but am displaying ASCII characters it seems.
int main(int argc, const char *argv[])
{
std::vector<char> memblock;
int i=0;
::std::ifstream in(argv[1], ::std::ios::binary);
while (in) {
char c;
in.get(c);
if (in) {
memblock.push_back(int(c));
i++;
//::std::cout << "Read a " << int(c) << "\n";
}
}
std::cout << "The contents of memblock are:";
for (std::vector<char>::iterator it = memblock.begin(); it != memblock.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
And also:
streampos size;
char * memblock;
ifstream file ("path", ios::in|ios::binary|ios::ate);
if (file.is_open())
{
size = file.tellg();
memblock = new char [size];
file.seekg (0, ios::beg);
file.read (memblock, size);
file.close();
cout << "the entire file content is in memory";
for(int i =0; i<10; i++){
cout << memblock[i+2000];
}
}
Is there an advantage to each approach? Or is there an even better method? Also how do I make sure to store the actual bit values or binary data from the binary file? Thank you