I'm solving this K&R exercise:
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.
So i was wandering if there's a site that contains source code for these string functions so i could check to see if i did something wrong.
These are the versions i wrote: i would appreciate if you would tell me if i have some bugs in the functions or something i should add/correct/improve!
int strncmp(char *s, char *t, int n)
{
if(strlen(s) == strlen(t)) {
while(*s == *t && *s && n)
n--, s++, t++;
if(!n)
return 0; /* same length and same characters */
else
return 1; /* same length, doesnt has the same characters */
}
else
return strlen(s) - strlen(t);
}
char *strncpy(char *s, char *t, int n)
{
while(n-- && *s) {
*s = *t;
s++, t++;
}
if(strlen(t) < n)
*s = '\0';
return s;
}
char *strncat2(char *s, char *t, int n)
{
while(*s)
s++;
while(n-- && *t)
*s = *t, s++, t++;
*s = '\0';
return s;
}