I want to write in 2 chars and a bit vector (uint64_t) to a file, but I first have to write them all to a buffer. Then the buffer will be written to the file. How should I write these 3 variables into a buffer (void pointer) so that all can be contained within one (void pointer) variable.
For example I want to write
char a = 'a';
char b = 'b';
uint64_t c = 0x0000111100001111;
into
void *buffer = malloc(sizeof(char)*2+sizeof(uint64_t));
Then write that into a file using
write(fd, buffer, sizeof(char)*2+sizeof(uint64_t));
This is the (almost*) completely safe way of doing it:
You might be tempted to do something like
*(uint64_t *)(buffer + 2) = c;but that’s not portable due to alignment restrictions.Note that
sizeof(char) == 1, per definition in the C standard.(*) I’ve assumed 8-bit
char, which is nearly, but not entirely universal; on a platform with 16-bitchar, usememcpyforaandbas well.