Skip to main content

Structure mapping

Posted in

Experience is such a thing, that comes to you as time goes. This happens to everybody, and sometimes when you learn a new thing, that you have never even thought about, you say to yourself: "Wow, you got to be an experienced person to know this".

I said that to myself many times as I worked in a team with people who are older and more experienced than me. And this always made be happy, the fact that I have an opportunity to learn. Some time ago I said that to myself once more, when I had to work with files of a specific format.

So, here is the problem (not the problem as when we are in trouble, but a problem that we have to solve efficiently). We have a file, which has a header, and we know its format. In our C application we have to operate with header's field, so we need
a structure for that header, and we need to fill that structure.

The way I would do (assuming that I don't know structure mapping technique) is I would open the file and read each field one by one into a temporary buffer and then copy the content of a buffer into a structure field.

But, here is how we will do this:

1. Define our structure (for example, as following)

struct Header
{
    char field1[LEN1];
    char field2[LEN2];
    // ...
};

2. Open the file for reading

int fd = open("/path/to/file", O_RDONLY);

3. Read the whole header to a buffer

char buf[HEADER_LEN];
read(fd, buf, HEADER_LEN); // it would be great to check read for failure

4. Map our structure

struct Header *header;
header = (struct Header*)buf;

5. We are done, our struct is ready for use.

Yes, I know, and I already hear some of you saying that the struct
fields are aligned and so on.

Nobody forbids me to do this:

#pragma pack(push, TurnOffMyStructAlignment, 1)
struct Header
{
    char field1[LEN1];
    char field2[LEN2];
    // ...
};
#pragma pack(pop, TurnOffMyStructAlignment)

Here comes the question, which way is easier? =)

Post new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
inte_est_ng: