Linux 如何写入缓冲区(空指针)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9625707/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I write to a buffer (void pointer)?
提问by Kobi
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.
我想将 2 个字符和一个位向量 (uint64_t) 写入文件,但我首先必须将它们全部写入缓冲区。然后缓冲区将被写入文件。我应该如何将这 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));
采纳答案by Fred Foo
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;
but that's not portable due to alignment restrictions.
您可能会想做一些类似*(uint64_t *)(buffer + 2) = c;
但由于对齐限制而无法移植的事情。
Note that sizeof(char) == 1
, per definition in the C standard.
请注意sizeof(char) == 1
,根据 C 标准中的定义。
(*) I've assumed 8-bit char
, which is nearly, but not entirely universal; on a platform with 16-bit char
, use memcpy
for a
and b
as well.
(*) 我假设了 8-bit char
,这几乎是通用的,但并不完全通用;在具有 16 位的平台上char
,也使用memcpy
fora
和b
。
回答by harald
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. 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:
或者像 cnicutar 建议的那样使用 memcpy。但是,我认为将每个元素一次写入文件要容易得多,而且不容易出错:
write(fd, &a, sizeof a);
write(fd, &b, sizeof b);
write(fd, &c, sizeof c);
Beware of endian issues.
小心字节序问题。