简体   繁体   English

如何写入缓冲区(空指针)?

[英]How can I write to a buffer (void pointer)?

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.我想将 2 个字符和一个位向量 (uint64_t) 写入文件,但我首先必须将它们全部写入缓冲区。 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.我应该如何将这 3 个变量写入缓冲区(空指针),以便所有变量都可以包含在一个(空指针)变量中。

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:这是(几乎*)完全安全的方法:

uint8_t *buffer = malloc(2 + sizeof(uint64_t));
buffer[0] = a;
buffer[1] = b;
memcpy(buffer + 2, &c, sizeof(c));

You might be tempted to do something like *(uint64_t *)(buffer + 2) = c;您可能会想做一些类似*(uint64_t *)(buffer + 2) = c;事情*(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.请注意,根据 C 标准中的定义, sizeof(char) == 1

(*) I've assumed 8-bit char , which is nearly, but not entirely universal; (*) 我假设了 8 位char ,这几乎但不完全通用; on a platform with 16-bit char , use memcpy for a and b as well.在具有 16 位char的平台上,对ab也使用memcpy

Well, you can allways put the data into a buffer like this:好吧,您始终可以将数据放入这样的缓冲区中:

void *buffer = malloc(size_of_buffer);
char *ch = buffer;
*pos++ = a;
*pos++ = b;
*(uint64_t*)(pos) = c

Or use memcpy like cnicutar suggests.或者像 cnicutar 建议的那样使用 memcpy。 However, I would think it's a lot easier and less error prone to just write each element to the file one at the time:但是,我认为将每个元素一次写入文件要容易得多,而且不容易出错:

write(fd, &a, sizeof a);
write(fd, &b, sizeof b);
write(fd, &c, sizeof c);

Beware of endian issues.小心字节序问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM