Question

How do read the data a compressed struct format in c++?

here is the data structure..

struct test
{
    unsigned int test3;
    unsigned char test1[4096];
    unsigned int test2;
} foo;

How do we read the structure written to a file using gzread?

Here is what i've tried.

gzread(Handle,&foo.test3, sizeof(&foo.test3)); //64
gzread(Handle,&foo.test1, sizeof(&foo.test1)); //4096
gzread(Handle,&foo.test2,sizeof(&foo.test2)); //4

However, the data I get is wrong. What is the mistake I'm doing?

An example of how to read a file saved in the format of struct would help me do it.

Was it helpful?

Solution

When you do &foo.test1 you get a pointer, and when you use sizeof on that pointer you get the size of the pointer and not what it points to. This will be, depending on platform, either 4 (for 32-bit platforms) or 8 (for 64-bit platforms).

For the code to work, you should drop the use of the & operand for the sizeof operations:

gzread(Handle, &foo.test3, sizeof(foo.test3));
gzread(Handle, &foo.test1, sizeof(foo.test1));
gzread(Handle, &foo.test2, sizeof(foo.test2));

However, it might still not be correct! What if the file was written to with another order? Or if the complete structure was written in one go, possible padding and all? You need to read it exactly as it was written.

Also, you have to make sure that the file was opened in binary mode, or you might get weird results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top