Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sprintf() without trailing null space in C

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.

like image 993
zaratustra Avatar asked Dec 10 '08 18:12

zaratustra


People also ask

Does sprintf include null?

The sprintf function returns the number of characters stored in the array s , not including the terminating null character.

Does Snprintf guarantee null termination?

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".

What does sprintf return in C?

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 .

Does Strcpy add NULL terminator?

The strcpy() function copies string2, including the ending null character, to the location that is specified by string1.


2 Answers

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.

like image 119
Greg Hewgill Avatar answered Sep 17 '22 17:09

Greg Hewgill


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>';
like image 41
Doug T. Avatar answered Sep 18 '22 17:09

Doug T.