/* * strncpy.c * * Copy one string to another. * Correctly terminate the new string and do not exceed its bounds. */ #include /* Copy src into dst; return the number of characters copied */ int strncpy(char dst[], const char src[], int dst_size) { int i; for (i=0; src[i] != '\0' && i < dst_size-1; i++) { dst[i] = src[i]; } dst[i] = '\0'; return i; } int main() { char from1[20] = ""; char from2[5] = ""; char to[10]; int char_copied; printf("Enter a string: \n"); fgets(from1, 20, stdin); char_copied = strncpy(to, from1, sizeof(to)); printf("%d characters copied; the destination string is: %s\n", char_copied, to); printf("Enter a string: \n"); fgets(from2, 5, stdin); char_copied = strncpy(to, from2, sizeof(to)); printf("%d characters copied; the destination string is: %s\n", char_copied, to); return 0; }