The function strncpy()
doesn\'t always null terminate so I want to know what is the best alternative that always null terminates?
I want a function that if:
As an alternative to the answer that suggested snprintf()
: (Note: trouble if n <= 0
)
size_t sz = sizeof buf;
/*n is the number of characters to be copied from source*/
int n = (int) sz - 1;
snprintf(buf, sz, "%s", src);
code can use the following precision:
"... the maximum number of bytes to be written for
s
conversions. ..." C11 §7.21.6.1 4
sprintf(buf, "%.*s", n, src);
It has the subtle advantage in that src
need not be a string, just an array of characters.
Another tool for strings.