Embedded Artistry libc
C Standard Library Support for Bare-metal Systems
strncpy.c File Reference
#include <string.h>
Include dependency graph for strncpy.c:

Go to the source code of this file.

Functions

char * strncpy (char *__restrict dst, const char *__restrict src, size_t maxlen)
 Copies at most maxlen characters of the character array pointed to by src to character array pointed to by dest. More...
 

Function Documentation

◆ strncpy()

char* strncpy ( char *__restrict  dst,
const char *__restrict  src,
size_t  maxlen 
)

Copies at most maxlen characters of the character array pointed to by src to character array pointed to by dest.

Copies at most maxlen characters of the character array pointed to by src (including the terminating null character, but not any of the characters that follow the null character) to character array pointed to by dest. If maxlen is reached before the entire array src was copied, the resulting character array is not null-terminated. If, after copying the terminating null character from src, maxlen is not reached, additional null characters are written to dest until the total of maxlen characters have been written.

The behavior is undefined if the character arrays overlap, if either dest or src is not a pointer to a character array (including if dest or src is a null pointer), if the size of the array pointed to by dest is less than maxlen, or if the size of the array pointed to by src is less than maxlen and it does not contain a null character.

Parameters
dstpointer to the character array to copy to
srcpointer to the character array to copy from
maxlenmaximum number of characters to copy
Returns
a copy of dest

Definition at line 26 of file strncpy.c.

27 {
28  const size_t srclen = strnlen(src, maxlen);
29  if(srclen < maxlen)
30  {
31  // The stpncpy() and strncpy() functions copy at most maxlen
32  // characters from src into dst.
33  memcpy(dst, src, srclen);
34  // If src is less than maxlen characters long, the remainder
35  // of dst is filled with '\0' characters.
36  memset(dst + srclen, 0, maxlen - srclen);
37  }
38  else
39  {
40  // Otherwise, dst is not terminated.
41  memcpy(dst, src, maxlen);
42  }
43  // The strcpy() and strncpy() functions return dst.
44  return dst;
45 }
size_t strnlen(const char *str, size_t maxlen)
Returns the length of the given null-terminated byte string.
Definition: strnlen.c:21
void * memset(void *dest, int c, size_t n)
Copies the value c into each of the first n characters of the object pointed to by dest.
void * memcpy(void *__restrict dest, const void *__restrict src, size_t n)
Copies n characters from the object pointed to by src to the object pointed to by dest.

References memcpy(), memset(), and strnlen().