strncat() appends at most n characters from the source string and then adds a terminating null character. The destination still needs enough capacity for its existing text, the appended characters and \0.
strncat(destination, source, n);
#include <stdio.h>
#include <string.h>
int main(void) {
char destination[30] = "welcome to ";
char source[] = "plus2net";
strncat(destination, source, 5);
printf("%s\n", destination);
return 0;
}
Output
welcome to plus2
#include <stdio.h>
#include <string.h>
int main(void) {
char destination[20] = "Plus2Net ";
char source[] = "C Tutorial";
size_t count = 5;
size_t available = sizeof(destination) - strlen(destination) - 1;
if (count > available) {
count = available;
}
strncat(destination, source, count);
printf("%s\n", destination);
return 0;
}
#include <stdio.h>
#include <string.h>
char *custom_strncat(char *destination, const char *source, size_t n) {
char *end = destination + strlen(destination);
while (*source != '\0' && n > 0) {
*end++ = *source++;
n--;
}
*end = '\0';
return destination;
}
int main(void) {
char destination[20] = "Hello, ";
custom_strncat(destination, "World!", 3);
printf("%s\n", destination);
return 0;
}
Output
Hello, Wor
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.