sprintf() without trailing null space in C

2020-05-19 04:20发布

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.

8条回答
Rolldiameter
2楼-- · 2020-05-19 04:46

Actually this example will not add a null if you use snprintf:

char name[9] = "QQ40dude";  
unsigned int i0To100 = 63;  
_snprintf(&name[2],2,"%d",i0To100);  
printf(name);// output will be: QQ63dude  
查看更多
我命由我不由天
3楼-- · 2020-05-19 04:49

You can't do this with sprintf(), but you may be able to with snprintf(), depending on your platform.

You need to know how many characters you are replacing (but as you're putting them into the middle of a string, you probably know that anyway).

This works because some implementations of snprintf() do NOT guarantee that a terminating character is written - presumably for compatibility with functions like stncpy().

char message[32] = "Hello 123, it's good to see you.";

snprintf(&message[6],3,"Joe");

After this, "123" is replaced with "Joe".

On implementations where snprintf() guarantees null termination even if the string is truncated, this won't work. So if code portability is a concern, you should avoid this.

Most Windows-based versions of snprintf() exhibit this behaviour.

But, MacOS and BSD (and maybe linux) appear to always null-terminate.

查看更多
登录 后发表回答