Emmanuel said:
Christian Bau said:
I suggest writing your own function, like
void my_strncpy (char* dst, const char* src, size_t maxlen)
{
if (strlen (src) < maxlen) {
strcpy (dst, src);
} else if (maxlen > 0) {
memcpy (dst, src, maxlen - 1);
dst [maxlen - 1] = '\0';
}
}
I think that scanning the string twice (strlen(), strcpy()) is not
a good idea. Here is my STR_safecopy() (from my personal library at
http://mapage.noos.fr/emdel)
You can also use a prototype that has been well tested (see
references) and, in my implementation, does not use the standard
library at all. If the names strlcpy/strlcat create any problems
change them. BSD systems, will not, I believe, need any
implementation whatsoever. This code is deliberately minimized,
for performance reasons.
Please read the reference at:
<
http://www.courtesan.com/todd/papers/strlcpy.html>
/* ------- file strlcpy.h ------- */
#ifndef strlcpy_h_
#define strlcpy_h_
#ifdef __cplusplus
extern "C" {
#endif
/* Implementation of strlcpy and strlcat
See
http://www.courtesan.com/todd/papers/strlcpy.html
These routines are explicitly designed to move no
data and simply return the projected size of the
final strings when called with sz == 0.
In addition they treat src == NULL as an empty string
strlcat expects that the sz parameter is greater than
the size of the dst string. If not, the treatment is
exactly the same as if a sz value of 0 was used.
NOTE: these routines are deliberately designed to
not require any assistance from the standard
libraries. This makes them more useful in any
embedded systems that must minimize the load size.
Public domain, by C.B. Falconer
bug reports to mailto:
[email protected]
*/
#include <stddef.h>
size_t strlcpy(char *dst, const char *src, size_t sz);
size_t strlcat(char *dst, const char *src, size_t sz);
#ifdef __cplusplus
}
#endif
#endif
/* ------- End file strlcpy.h ------- */
/* ------- file strlcpy.c ------- */
#include "strlcpy.h"
/* ---------------------- */
size_t strlcpy(char *dst, const char *src, size_t sz)
{
const char *start = src;
if (src && sz--) {
while ((*dst++ = *src))
if (sz--) src++;
else {
*(--dst) = '\0';
break;
}
}
if (src) {
while (*src++) continue;
return src - start - 1;
}
else if (sz) *dst = '\0';
return 0;
} /* strlcpy */
/* ---------------------- */
size_t strlcat(char *dst, const char *src, size_t sz)
{
char *start = dst;
while (*dst++) /* assumes sz >= strlen(dst) */
if (sz) sz--; /* i.e. well formed string */
dst--;
return dst - start + strlcpy(dst, src, sz);
} /* strlcat */
/* testing code snipped */
/* ------- End file strlcpy.c ------- */
Some comments and testing have been snipped. The unaltered files
are available at:
<
http://cbfalconer.home.att.net/download/strlcpy.zip>