How to append string using snprint() function
#include<stdio.h>
main()
{
char str[50] = "Wel %s";
char dst[50];
snprintf(dst,50,str,"Come");
//Now i want to append "*" to dst string ie "Wel Come*" using snprintf()
printf("str = %s\n",str);
p开发者_如何学Gorintf("dst = %s\n",dst);
}
please suggest is it possible using snprintf()
Thanks Surya
The obvious solution:
snprintf(dst,50,"%s*",dst);
is inefficient, because it makes an unnecessary copy of dst
(into itself).
invokes undefined behavior as R. pointed out, because the arguments may not overlap (from man snprintf(3) on MacOSX):
"[...]or those routines that write to a user-provided character string, that string and the format strings should not overlap, as the behavior is undefined."
Posix says:
- http://www.opengroup.org/onlinepubs/000095399/functions/printf.html
"If copying takes place between objects that overlap as a result of a call to sprintf() or snprintf(), the results are undefined."
snprintf
returns the number of characters it has written, so you can do this instead:
int k=snprintf(dst,50,str,"Come");
// make sure that we do not pass potential disastrous values to snprintf, because
// the size argument is unsigned (size_t, 50-52 is a large positive number!)
// and we want 50-k to be in the range 0-50
// k<0 means output error and k>50 means "output truncated". There is no point in
// appending anything in these cases anyway.
if (k<0 || k>50)
{
fprintf(stderr,"output error or buffer too small");
}
else k=snprintf(dst+k,50-k,"*");
// check k for truncation here.
And then there's always strcat
...And just in case, you overlooked it. You can have the * attached right in the first place:
main()
{
char str[50] = "Wel %s*"; //<--!!!
[...]
This should work:
#include<stdio.h>
int main()
{
char str[50] = "Wel %s";
char dst[50];
int len;
snprintf(dst,50,str,"Come");
//get size of current string
len = strlen(dst);
//add character to the end
snprintf(dst + len, sizeof(dst) - len, "*");
printf("str = %s\n",str);
printf("dst = %s\n",dst);
return 0;
}
you can use the %s
format for this:
snprintf(dst, 50, "%s*", dst);
EDIT: This seems to have some undefined behaviors. The best thing would be to ask if it is really necessary to use snprintf
instead of strncat
.
All the information is already available to you:
snprintf(dst + 8, sizeof(dst) - 8, "%s", "*");
You'd be better off doing:
strncat(dst, "*", sizeof(dst) - strlen(dst) - 1);
精彩评论