Did you consider using flexible array members (also explained here)? See this... So declare
struct msg_t {
unsigned length;
char msg[];
};
allocate it with e.g.
struct msg_t* make_msg(unsigned l) {
// one extra byte for the terminating null char
struct msg_t* m = malloc(sizeof(struct msg_t)+l+1;
if (!m) { perror("malloc m"); exit(EXIT_FAILURE); };
memset(m, 0, sizeof(struct msg_t)+l+1);
m->length = l;
return m;
}
then write it with e.g.
fwrite(m, sizeof(struct msg_t)+m->length+1, 1, fil);
or if you use write
do the buffering yourself (since a write
can be partial!) e.g.
void write_msg(int fd, struct msg_t *m) {
assert(m != NULL);
char* b = m;
unsigned siz = sizeof(struct msg_t)+m->length+1);
while (siz>0) {
int cnt=write (fd, b, siz);
if (cnt<0) { perror("write"); exit(EXIT_FAILURE); };
b += cnt;
siz -= cnt;
}
}