1

I am trying to read mixed data into a C struct

usually, I do something like this

typedef struct data {
    uint32_t value;
    float x,y,z;
} __attribute__((__packed__));

and read it in like so:

data x;
fread(&x, 1, sizeof(data), filePointer);

and that works just fine for fixed length data, however, I need to load a ASCIIZ string, which is variable length, and I was wondering if there was a easy way to read that into a struct

Nick Beeuwsaert
  • 1,598
  • 1
  • 11
  • 18
  • 1
    On most common systems, `__attribute__((__packed__))` will do nothing here, since `uint32_t` and `float` are often both 4 bytes. – Chris Lutz Aug 06 '11 at 05:34

2 Answers2

1

Sorry, but there is no built-in serialization for C. This has been asked on SO before with some very good answers.

If that doesn't give you what you want, then search for C serialize or C serialization in your favorite search engine.

Community
  • 1
  • 1
unpythonic
  • 4,020
  • 19
  • 20
1

There are two ways you could be storing your ASCIIZ string in the structure, exemplified by:

struct asciiz_1
{
    char asciiz[32];
};
struct asciiz_2
{
    size_t buflen;
    char  *buffer;
};

The first (struct asciiz_1) can be treated the same way as your struct data; even though the string may be of variable length with garbage after the null (zero) byte, the structure as a whole is a fixed size and can be handled safely with fread() and fwrite().

The second (struct asciiz_2) is a lost cause. You have to allocate the extra space to receive the string (presumably after reading the length), and the pointer value should not be written to the file (it won't have any meaning to the reading process). So, you have to handle this differently.

Your data structure - your choice.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • If using C99 (or willing to do some terrible things), there's always `struct ascizz_3 { size_t buflen; char buffer[]; };` GCC even lets you statically initialize `struct`s with flexible array members. – Chris Lutz Aug 06 '11 at 08:06