65 lines
1.5 KiB
C
65 lines
1.5 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
|
|
char *strncpy(char *t, const char *s, size_t n);
|
|
char *strncat(char *t, const char *s, size_t n);
|
|
int strncmp(const char *s, const char *t, size_t n);
|
|
|
|
/* strlen: returns string length (w/o '\0') */
|
|
size_t strlen(const char *s)
|
|
{
|
|
const char * const sc = s;
|
|
while (*s++)
|
|
;
|
|
return s - sc - 1;
|
|
}
|
|
|
|
/* takes args s1, s2, n and passes them to the above declared
|
|
* functions, prints the results */
|
|
int main(int argc, char *argv[])
|
|
{
|
|
if (argc < 4)
|
|
return 1;
|
|
|
|
int n = atoi(argv[3]);
|
|
char s[strlen(argv[1]) + strlen(argv[2]) + 1];
|
|
/* strncpy */
|
|
printf("strncpy: %s\n", strncpy(s, argv[1], n));
|
|
/* strncat */
|
|
printf("strncat: %s\n", strncat(s, argv[2], n));
|
|
/* strncmp */
|
|
int comp = strncmp(argv[1], argv[2], n);
|
|
printf("strncmp: %.*s ", n, argv[1]);
|
|
putchar((comp > 0) ? '>' : (comp < 0) ? '<' : '=');
|
|
printf(" %.*s\n", n, argv[2]);
|
|
|
|
return 0;
|
|
}
|
|
|
|
/* strncpy: copies at most n chars from s to t, returns t*/
|
|
char *strncpy(char *t, const char *s, size_t n)
|
|
{
|
|
char * const tc = t;
|
|
while (n-- && (*t++ = *s++))
|
|
;
|
|
*t = '\0';
|
|
return tc;
|
|
}
|
|
|
|
/* strncat: concats at most n chars of s to t, returns t */
|
|
char *strncat(char *t, const char *s, size_t n)
|
|
{
|
|
strncpy(t + strlen(t), s, n);
|
|
return t;
|
|
}
|
|
|
|
/* strncmp: compares at most n chars of s and t */
|
|
int strncmp(const char *s, const char *t, size_t n)
|
|
{
|
|
if (!n)
|
|
return 0;
|
|
while (--n && *s && (*s == *t))
|
|
s++, t++;
|
|
return *s - *t;
|
|
}
|