Multiple Null Terminated Lines in a Single Buffer in C

It is necessary to create a line with the following format and place it in one buffer [1000]. Note that \ x00 is the null terminator.

@/foo\x00ACTION=add\x00SUBSYSTEM=block\x00DEVPATH=/devices/platform/goldfish_mmc.0\x00MAJOR=command\x00MINOR=1\x00DEVTYPE=harder\x00PARTN=1

So essentially I need to pack the following lines with zero completion in one buffer

@/foo  
ACTION=add  
SUBSYSTEM=block  
DEVPATH=/devices/platform/goldfish_mmc.0  
MAJOR=command  
MINOR=1  
DEVTYPE=harder  
PARTN=1  

How can i do this?

+4
source share
3 answers

You will need to copy each line one at a time, keeping track of where the last copy is stopped and starting right after that for the next.

char *p = buffer;
strcpy(p, "@/foo");
p += strlen(p) + 1;
strcpy(p, "ACTION=add");
p += strlen(p) + 1;
...
+3
source

You can use %cto print a numeric zero with sprintf, for example:

char *a[] = {"quick", "brown", "fox", "jumps"};
int n = 0;
char buf[100];
for (int i = 0 ; i != 4 ; i++) {
    n += sprintf(buf+n, "%s%c", a[i], 0);
}

Demo

+3
source

, 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";

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));

, NUL; NUL.

In addition, splitting a string, such as "\01"(which does not actually appear in this case), "\0" "1"prevents the compiler from seeing "\01"as one character string { 0x01, 0x00 }(with an implicit trailing NUL), and instead treats it as two character strings { 0x00, 0x31, 0x00 }(also with an implicit trailing NUL), which was intended.

+3
source

Source: https://habr.com/ru/post/1689975/


All Articles