User defined function of strcpy()
strncpy is used to copies first n character of a string to another.
Prototype of strncpy() function : char* strncpy(char *dest, const char *src, size_t n);
Program of strncpy()
#include <stdio.h>
char* own_strncpy(char *dest, const char *src, int n)
{
char *temp = dest;
/* copy of string from source to destination up to n characters */
while (n–)
{
(*dest++ = *src++);
}
*dest = ‘\0’;
return temp;
}
int main()
{
char src_str[50];
char dest_str[50];
int num_of_char;
char *dest = NULL;
printf(“Enter any string = “);
gets(src_str);
printf(“Enter number of character copy to destination = “);
scanf(“%d”,&num_of_char);
/* Own string copy function call */
dest = own_strncpy(dest_str, src_str, num_of_char);
printf(“Destination string is = %s”,dest);
return 0;
}
Output:
$ ./a.exe
Enter any string = gyantoday
Enter number of character copy to destination = 4
Destination string is = gyan