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.
相关问题
- Multiple sockets for clients to connect to
- how to split a list into a given number of sub-lis
- What means in Dart static type and why it differs
- What is the best way to do a search in a large fil
- glDrawElements only draws half a quad
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.
Here's an option for memory constrained devices. It trades off speed for using less RAM. I sometimes have to do this to update the middle of a string that gets printed to a LCD.
The idea is that you first call snprintf with a zero sized buffer to determine which index will get clobbered by the null terminator.
You can run the below code here: https://rextester.com/AMOOC49082
Prints
buf:123de
look here: http://en.wikipedia.org/wiki/Printf
There is no way to tell
sprintf()
not to write a trailing null. What you can do is usesprintf()
to write to a temporary string, and then something likestrncpy()
to copy only the bytes that you want.You could also use your fixed width string as a format string like this:
should yield
Since you're writing to a fixed area, you can do it like this: