Search code examples
cstructfreadfseek

fread fseek struct member only in C


In C I'm trying to select a specific member of a struct and print it out. I wonder, what is the suggested format for such an operation? I've tried nearly everything I can think of. I can't seem to limit it to the specific chunk member of the struct.

fseek(in, sizeof(d.contents.datas.chunk), SEEK_SET);
fread(&ch, 1, 1, in);
fprintf(out, "%02x", (int)(ch & 0x00FF));

It seems I can get either all of the struct data, or only one character. For some reason the data is also not coming out right, for instance bytes should be the actual bytes, but it's coming out as 1. Clearly there is something really wrong with the way the data from this struct is being printed. Could it be to do with big endian vs little endian? I know the file I'm accessing is big endian.

The struct Im accessing is as follows:

struct chunkInfo
{
    int chunkInformation; 
    int bytes;

    union
    {
        struct
        {
            long size;     
            char chunk[1];     
        } datas;                 
    } contents;                  
};

Solution

  • You are seeking to the wrong place in the file. Assuming the endian of your machine is the same as the endian of the file, then this will work:

    fseek(in, long(&d.content.data.chunk[0] - &d), SEEK_SET);
    fread(&ch, 1, 1, in);
    fprintf(out, "%02x", (int)(ch & 0x00FF));
    

    The first line calculates the offset in bytes of chunk in the structure. You were using the sizeof(chunk) which of course just returns 1.

    If the endian is different, then you will have to convert each non char character to the correct endian after reading in the structure.