I would want to know how is it possible to escape “%*s” in a sprintf call.
For example I have the following piece of code:
sprintf(log_buffer,"1234 567 89");
strcpy(format,"%*s");
sprintf(format1, " %%%ds %%%ds ",5,5);
printf("\n Format is : %s ",format);
printf("\n Format1 is : %s ",format1);
strcat(format,format1);
printf("\n new format is : %s ",format);
sscanf(log_buffer,format,name,name1);
printf(" Name is 1: %s \n",name);
printf(" Name is 2: %s ",name1);
This works fine.
It gives me:
Format is : %*s
Format1 is : %5s %5s
new format is : %*s %5s %5s
Name is 1: 567
Name is 2: 89
Can I possibly not use strcpy and ignore the %*s within the sprintf itself? I tried escaping it inside sprintf but I guess it’s not proper as I get a Segmentation fault.
sprintf(format1, " \%*s %%%ds %%%ds ",5,5);
It looks like you already know how to escape
%signs insprintf(by prefixing with another%) – you’re doing it correctly for%%%ds.What you want is:
Edit: The reason it’s segfaulting is because
\%*sis interpreted as a literal backslash, followed by a NULL-terminated string; sosprintfis trying to interpret 5 as a NULL-terminated string, which it patently isn’t. It’ll be running off into forbidden memory looking for a NULL-byte, and segfaulting.