strncpy() — Copy Strings

Format

#include <string.h>
char *strncpy(char *string1, const char *string2, size_t count);

Language Level: ANSI

Threadsafe: Yes.

Description

The strncpy() function copies count characters of string2 to string1. If count is less than or equal to the length of string2, a null character (\0) is not appended to the copied string. If count is greater than the length of string2, the string1 result is padded with null characters (\0) up to length count.

Return Value

The strncpy() function returns a pointer to string1.

Example that uses strncpy()

This example demonstrates the difference between strcpy() and strncpy().

#include <stdio.h>
#include <string.h>
 
#define SIZE    40
 
int main(void)
{
  char source[ SIZE ] = "123456789";
  char source1[ SIZE ] = "123456789";
  char destination[ SIZE ] = "abcdefg";
  char destination1[ SIZE ] = "abcdefg";
  char * return_string;
  int    index = 5;
 
  /* This is how strcpy works */
  printf( "destination is originally = '%s'\n", destination );
  return_string = strcpy( destination, source );
  printf( "After strcpy, destination becomes '%s'\n\n", destination );
 
 
  /* This is how strncpy works */
  printf( "destination1 is originally = '%s'\n", destination1 );
  return_string = strncpy( destination1, source1, index );
  printf( "After strncpy, destination1 becomes '%s'\n", destination1 );
}
 
/*****************  Output should be similar to:  *****************
 
destination is originally = 'abcdefg'
After strcpy, destination becomes '123456789'
 
destination1 is originally = 'abcdefg'
After strncpy, destination1 becomes '12345fg'
*/

Related Information



[ Top of Page | Previous Page | Next Page | Contents | Index ]