strncat() — Concatenate Strings

Format

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

Language Level: ANSI

Threadsafe: Yes.

Description

The strncat() function appends the first count characters of string2 to string1 and ends the resulting string with a null character (\0). If count is greater than the length of string2, the length of string2 is used in place of count.

The strncat() function operates on null-ended strings. The string argument to the function should contain a null character (\0) marking the end of the string.

Return Value

The strncat() function returns a pointer to the joined string (string1).

Example that uses strncat()

This example demonstrates the difference between strcat() and strncat(). The strcat() function appends the entire second string to the first, whereas strncat() appends only the specified number of characters in the second string to the first.

#include <stdio.h>
#include <string.h>
 
#define SIZE 40
 
int main(void)
{
  char buffer1[SIZE] = "computer";
  char * ptr;
 
  /* Call strcat with buffer1 and " program" */
 
  ptr = strcat( buffer1, " program" );
  printf( "strcat : buffer1 = \"%s\"\n", buffer1 );
 
  /* Reset buffer1 to contain just the string "computer" again */
 
  memset( buffer1, '\0', sizeof( buffer1 ));
  ptr = strcpy( buffer1, "computer" );
 
  /* Call strncat with buffer1 and " program" */
  ptr = strncat( buffer1, " program", 3 );
  printf( "strncat: buffer1 = \"%s\"\n", buffer1 );
}
 
/*****************  Output should be similar to:  *****************
 
strcat : buffer1 = "computer program"
strncat: buffer1 = "computer pr"
*/

Related Information



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