I think I saw this on BWK's home page somewhere, but I can't find it at the moment.
strncpy() was originally designed for certain unix data structures which contained fixed length strings with an optional \0 (eg filenames in inodes).
Since everyone knew the size of the string, the lack of a \0 was not a particular problem.
The problems arise when trying to use strncpy() to always guarantee a \0 terminated string, and then people remark on the lack of a guaranteed \0.
Basically, it's a relic of the past - like gets() - which has little or no use in todays programming environments.
If you don't care about whether the string is too long, then something like
Code:
char *strlcpy ( char *dest, const char *src, size_t len ) {
strncpy( dest, src, len );
dest[len-1] = '\0';
return dest;
}
Returns dest, in keeping with the other str functions
Or perhaps
Code:
int strlcpy ( char *dest, const char *src, size_t len ) {
int res;
strncpy( dest, src, len );
res = dest[len-1];
dest[len-1] = '\0';
return res;
}
This returns 0 if the string fitted in the buffer, or non-zero if the source string was too big.