I am using snprintf to concatenate a string to a char array:
char buf[20] = "";
snprintf(buf, sizeof buf, "%s%s", buf, "foo");
printf("%s\n", buf);
snprintf(buf, sizeof buf, "%s%s", buf, " bar");
printf("%s\n", buf);
The problem is the second concatenation to buf instead of adding "bar", replaces "foo" with it. The output is like:
foo
bar
The first %s should keep buf (which in this case holds "foo") there. And the second %s should attach "bar" to it. Right?
What am I doing wrong?
You’re violating the
restrictcontract onsnprintf, which states that no other argument can overlap the buffer.Copying the input into itself is a waste of effort anyway.
snprintfreturns the number of characters which formatting would require, so take advantage of this for appending: