6.20.16 strncat Function
Append a specified number of characters from the source string to the destination string.
Include
<string.h>
Prototype
char *strncat(char *s1, const char *s2, size_t
n);
Arguments
s1
- destination string to copy to
s2
- source string to copy from
n
- maximum number of characters to append
Return Value
Returns a pointer to the destination string.
Remarks
This function appends up to n
characters (a null character
and characters that follow it are not appended) from the source string to the end of the
destination string. If a null character is not encountered, then a terminating null
character is appended to the result. If the strings overlap, the behavior is
undefined.
Example
See the notes at the beginning of this chapter or section for
information on using printf()
or scanf()
(and other functions reading and writing the stdin
or
stdout
streams) in the example code.
#include <string.h>
#include <stdio.h>
int main(void)
{
char buf1[50] = "We're here";
char buf2[50] = "Where is the time?";
char buf3[50] = "Why?";
printf("buf1 : %s\n", buf1);
printf("\t(%d characters)\n\n", strlen(buf1));
printf("buf2 : %s\n", buf2);
printf("\t(%d characters)\n\n", strlen(buf2));
printf("buf3 : %s\n", buf3);
printf("\t(%d characters)\n\n\n", strlen(buf3));
strncat(buf1, buf2, 6);
printf("buf1 after strncat of 6 characters "
"of buf2: \n\t%s\n", buf1);
printf("\t(%d characters)\n", strlen(buf1));
printf("\n");
strncat(buf1, buf2, 25);
printf("buf1 after strncat of 25 characters "
"of buf2: \n\t%s\n", buf1);
printf("\t(%d characters)\n", strlen(buf1));
printf("\n");
strncat(buf1, buf3, 4);
printf("buf1 after strncat of 4 characters "
"of buf3: \n\t%s\n", buf1);
printf("\t(%d characters)\n", strlen(buf1));
}
Example Output
buf1 : We’re here
(10 characters)
buf2 : Where is the time?
(18 characters)
buf3 : Why?
(4 characters)
buf1 after strncat of 6 characters of buf2:
We’re hereWhere
(16 characters)
buf1 after strncat of 25 characters of buf2:
We’re hereWhere Where is the time?
(34 characters)
buf1 after strncat of 4 characters of buf3:
We’re hereWhere Where is the time?Why?
(38 characters)