Is there a way to use the C sprintf() function without it adding a '\0' character at the end of its output? I need to write formatted text in the middle of a fixed width string.
The sprintf function returns the number of characters stored in the array s , not including the terminating null character.
snprintf ... Writes the results to a character string buffer. (...) will be terminated with a null character, unless buf_size is zero. So all you have to take care is that you don't pass an zero-size buffer to it, because (obviously) it cannot write a zero to "nowhere".
sprintf() in C int sprintf(char *str, const char *string,...); Return: If successful, it returns the total number of characters written excluding null-character appended in the string, in case of failure a negative number is returned .
The strcpy() function copies string2, including the ending null character, to the location that is specified by string1.
There is no way to tell sprintf()
not to write a trailing null. What you can do is use sprintf()
to write to a temporary string, and then something like strncpy()
to copy only the bytes that you want.
sprintf returns the length of the string written (not including the null terminal), you could use that to know where the null terminal was, and change the null terminal character to something else (ie a space). That would be more efficient than using strncpy.
unsigned int len = sprintf(str, ...);
str[len] = '<your char here>';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With