1

My main problem is that when reading any .zip file, it isn't reading the data into the struct properly and so the filenameLength property is set to 0 even though it should be correct. I tested with zip.seekg(26) and read that value which gave me the correct value, which makes me think something is wrong with my struct. So I printed out the size of my struct and it gave off 32 even though all the property sizes added up equals 30. What am I doing wrong?

struct ZIPHeader
{
    int sig; // 4
    short versionMadeBy; // 6
    short extractorversion; // 8
    short genflag; // 10
    short lastModificationTime; // 12
    short lastModificationDate; // 14
    int crc; // 18
    int compressedSize; // 22
    int uncompressedSize; // 26
    short filenameLength; // 28
    short extraFieldLength; // 30
} zheader;

void PrintZipInfo(const char* dir)
{
    cout << "Sizeofheader: " << sizeof(ZIPHeader) << endl;
    ifstream zip(dir, ios::binary);
    zip.read((char *)&zheader, sizeof(ZIPHeader));
    cout << "File name length: " << zheader.filenameLength << endl;
}

Outputs

Sizeofheader: 32

File name length: 0

Community
  • 1
  • 1
  • C++ allows for structures to have arbitrary padding. Also, you're assuming that `sizeof(int)=4`. You're in for some rude surprise when you try to compile your code on a 64-bit platform. If you need to parse a specific binary file-based structure, the only practical way to do is to dump it into an opaque `char` buffer, then pluck out all the individual fields, byte by byte, yourself. – Sam Varshavchik Oct 27 '17 at 01:11
  • Implement proper deserialization. Reading a chunk of binary data into a structure is bound to fail in odd ways. To begin with, the numbers you wrote on the side can change: C++ does not guarantee size of types. – spectras Oct 27 '17 at 01:15

0 Answers0