Chapter Contents

Previous

Next
strncpy

strncpy



Copy a Limited Portion of a Null-Terminated String

Portability: ISO/ANSI C conforming, UNIX compatible


SYNOPSIS
DESCRIPTION
RETURN VALUE
CAUTION
PORTABILITY
EXAMPLE
RELATED FUNCTIONS
SEE ALSO


SYNOPSIS

#include <string.h>

char *strncpy(char *to, const char *from, size_t maxlen);


DESCRIPTION

strncpy copies characters from the second argument string ( from ) to the first argument string ( to ) until a terminating-null character is found or until the number of characters specified by maxlen have been copied. If the maximum number of characters is reached, a terminating-null character is not added. If fewer than maxlen characters are copied, the to string is padded with enough null characters to bring the total number of characters copied to maxlen .


RETURN VALUE

The return value is a pointer to the to string.


CAUTION

If the to and from areas overlap, the effect of strncpy is not defined.

If the maxlen value is 0, no characters are copied. If the value is negative, it is interpreted as a very large unsigned number, probably causing massive overlay of memory.

Note:    At the conclusion of a call to strncpy , the target string may not be null terminated.  [cautionend]


PORTABILITY

Many implementations before ANSI C do not pad the target of strncpy with more than a single null.


EXAMPLE

#include <string.h>
#include <stdio.h>

main()
{
   char *phrase = "It is almost 4:30 in the afternoon.";
   char after[11] ;
   char *colon;

   colon = strchr(phrase, ':');
   if (!colon)
      puts("No colon found in string.");
   else{
       strncpy(after, colon+1, 10); /* Copy up to 10 characters */
                                    /*  after a colon.          */
       after[10] = '\0';
       printf("Text following colon is - %s\n", after);
                                  /* should print "30 in the ". */
   }
   return;
}


RELATED FUNCTIONS

memcpy , strncat , strcpy


SEE ALSO


Chapter Contents

Previous

Next

Top of Page

Copyright © 2001 by SAS Institute Inc., Cary, NC, USA. All rights reserved.