Search code examples
c++binaryfiles

Having trouble understanding binary file reading


Below is some code I found which to my minimal understanding reads in a binary file. I have commented what I believe to be happening however i'm having trouble recognizing what exactly memblock is/ what it is storing. Is it the entire binary file?

void BinaryFiles(string sfile){
    streampos size;                               //creates object to store size of file
    unsigned char* memblock;
    ifstream file(sfile, ios::in | ios::binary);  //creates file object(which opens file)
    if (file.is_open())
    {
        file.seekg(0, ios::end);                 //find end of file
        size = file.tellg();                     //sets size equal to distance from beginning
        memblock = new unsigned char[size];      //dynamically allocates memblock to char array
        file.seekg(0, ios::beg);                 //find beginning of file
        file.read((char*)memblock, size);        //this is where confusion begins
        cout << memblock << endl;                //what am I printing?
        file.close();
        delete[] memblock;
}
}

Solution

  • //this is where confusion begins

    OK, so then let's start here:

    file.read((char*)memblock, size); 
    

    This tells the ifstream to read a specific number (size) of bytes into some memory buffer you provide as pointer (memblock).

    However, read accepts a pointer to char, but the buffer was created as unsigned char, so we cast.

    cout << memblock << endl;
    

    will output the content of the file you've just read. Actually, it will only print until the first null character encountered, so it might truncate the file contents. Howver, if the file doesn't contain a null character at all, you get undefined behaviour as operator<< then will read beyond the buffer's bounds.