[英]multiple null terminated strings in single buffer in C
In need to craft a string with the following format and place it into a single buffer[1000]. 需要使用以下格式制作字符串并将其放入单个缓冲区[1000]。 Note that \\x00 is the null terminator. 请注意\\ x00是空终止符。
@/foo\x00ACTION=add\x00SUBSYSTEM=block\x00DEVPATH=/devices/platform/goldfish_mmc.0\x00MAJOR=command\x00MINOR=1\x00DEVTYPE=harder\x00PARTN=1
So in essence I need to pack following null terminated strings into a single buffer 所以本质上我需要将以下空终止字符串打包到单个缓冲区中
@/foo
ACTION=add
SUBSYSTEM=block
DEVPATH=/devices/platform/goldfish_mmc.0
MAJOR=command
MINOR=1
DEVTYPE=harder
PARTN=1
How might I go about doing this? 我该怎么做呢?
You'll need to copy each string in one at a time, keeping track of where the last copy stopped and starting just after that for the next one. 您需要一次一个地复制每个字符串,跟踪最后一个副本停止的位置,然后在下一个副本之后开始。
char *p = buffer;
strcpy(p, "@/foo");
p += strlen(p) + 1;
strcpy(p, "ACTION=add");
p += strlen(p) + 1;
...
You can initialize your buffer with a string containing explicit embedded NUL characters: 您可以使用包含显式嵌入式NUL字符的字符串初始化缓冲区:
char buffer[1000] =
"@/foo\0"
"ACTION=add\0"
"SUBSYSTEM=block\0"
"DEVPATH=/devices/platform/goldfish_mmc.0\0"
"MAJOR=command\0"
"MINOR=1\0"
"DEVTYPE=harder\0"
"PARTN=1";
Or you can copy it explicitly with memcpy
: 或者您可以使用memcpy
显式复制它:
char str[] =
"@/foo\0"
"ACTION=add\0"
"SUBSYSTEM=block\0"
"DEVPATH=/devices/platform/goldfish_mmc.0\0"
"MAJOR=command\0"
"MINOR=1\0"
"DEVTYPE=harder\0"
"PARTN=1";
char buffer[1000];
memcpy(buffer, str, sizeof(str));
Here, the compiler will concatenate adjacent string constants, but only the last string will get an implicit NUL; 在这里,编译器将连接相邻的字符串常量,但只有最后一个字符串将获得一个隐式NUL; all others have an explicit NUL. 所有其他人都有明确的NUL。
Also, breaking up a string like "\\01"
(which doesn't actually appear in this case) into "\\0" "1"
prevents the compiler from seeing the "\\01"
as the single character string { 0x01, 0x00 }
(with implicit trailing NUL), and instead treats is as the two character string { 0x00, 0x31, 0x00 }
(also with an implicit trailing NUL) that was intended. 另外,将"\\01"
(在这种情况下实际上不会出现)这样的字符串分解为"\\0" "1"
阻止编译器将"\\01"
视为单个字符串{ 0x01, 0x00 }
(使用隐式尾随NUL),而是将fors视为两个字符串{ 0x00, 0x31, 0x00 }
(也带有隐式尾随NUL)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.