Complete.Org:
Mailing Lists:
Archives:
freeciv-dev:
August 1999: [Freeciv-Dev] patch: zstrncpy() (PR#112) |
[Freeciv-Dev] patch: zstrncpy() (PR#112)[Date Prev][Date Next][Thread Prev][Thread Next][Date Index] [Thread Index]
This patch adds and uses a new function zstrncpy: /****************************************************************** * zstrncpy(): * * Like strncpy(), but with some features to make it easier to * keep strings null-terminated. In particular, always writes * a terminating null, including when input is longer than n. * * Eg, often see code like: * strncpy(dest, src, sizeof(dest)); * dest[sizeof(dest)-1] = '\0'; * or sometimes just: * strncpy(dest, src, sizeof(dest)-1); * if one can be sure dest[] is initially filled with nulls. * With zstrncpy can now omit second line, without needing above * contraint, and just do: * zstrncpy(dest, src, sizeof(dest)); * * Also, zstrncpy() does not pad dest with nulls if src is * shorter than n (doing so could be inefficient if n is large * and src happens to be short). * * Also, return value is different from strncpy: zstrncpy returns * the number of chars written, not including the trailing null. * (This is intended to help keep track when cat-ing to a buffer.) * * It is an error to call this with (n <= 0), or with * either dest or src NULL. * * Yes, n should probably be size_t, but int is enough for me. *****************************************************************/ int zstrncpy(char *dest, const char *src, int n) { assert(dest); assert(src); assert(n>0); { char * const start = dest; char * const final = dest + n - 1; while( (dest <= final) && ((*dest++ = *src++)) ) ; *--dest = '\0'; return dest - start; } } (Actually, as I post this it now occurs to me that it may be more useful to just return 0 if (n<=0), for case when cat-ing to a buffer and decrementing the space remaining.) Regards, -- David
zstrncpy1.diff.gz
|