Page 107

Write versions of the library functions strncpy, strncat, and strncmp, which operate on at most the first n characters of their argument strings. For example, strncpy(s,t,n) copies at most n characters of t to s. Full descriptions are in Appendix B.

#include <stdio.h>
#define MAX 1000

char *str_ncpy(char *s, char *t, int n);
char *str_ncat(char *s, char *t, int n);
int str_ncmp(char *s, char *t, int n);

int main()
{
	char str1[MAX] = "Hello";
	char *str2 = " world!";
	char *str3 = "Hello world!";
	char *str4 = "Hello England!";
	char str5[MAX] = "overwrite me";

	int ncopy = 7;
	printf("Copy %d chars of '%s' to str5; result: '%s'\n", ncopy, str1,
	       str_ncpy(str5, str1, ncopy));

	int ncat = 6;
	printf("Concatenate %d chars of '%s' to str1; result: '%s'\n", ncat,
	       str2, str_ncat(str1, str2, ncat));

	int ncmp = 5;
	printf("Compare %d chars of '%s' to '%s'; result: %d\n", ncmp, str3,
	       str1, str_ncmp(str3, str1, ncmp));

	ncmp = 10;
	printf("Compare %d chars of '%s' to '%s'; result: %d\n", ncmp, str3,
	       str4, str_ncmp(str3, str4, ncmp));
}

char *str_ncpy(char *s, char *t, int n)
{
	char *orig = s;
	for (; n > 0 && *t != '\0'; n--, s++, t++) {
		*s = *t;
	}

	for (; n > 0; n--, s++) {
		*s = '\0';
	}

	return orig;
}

char *str_ncat(char *s, char *t, int n)
{
	char *orig = s;

	for (; *s != '\0'; s++)
		;

	for (; n > 0 && *t != '\0'; n--, s++, t++) {
		*s = *t;
	}

	for (; n > 0; n--, s++) {
		*s = '\0';
	}

	return orig;
}

int str_ncmp(char *s, char *t, int n)
{
	for (; *s == *t; s++, t++, n--) {
		if (*s == '\0' || n == 0) {
			return 0;
		}
	}
	return *s - *t;
}