summaryrefslogtreecommitdiffstats
path: root/5/5.c
blob: 84bd57ad2dc97e56d71d7c7b3dafd0dfedda8e77 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAXLEN 1000

void mstrncpy(char *s, char *t, int n);
void mstrncat(char *s, char *t, int n);
int mstrncmp(char *s, char *t, int n);

/* Versions of strncpy, strncat and strncmp upto n most char */
int main(int argc, char *argv[]) {
  int n;
  char *s, *t;

  n = 5;
  s = malloc(sizeof(char) * MAXLEN);
  t = "hello, world!";

  mstrncpy(s, t, n);
  printf("mstrncpy: %s\n", s);

  n = 7;
  t = "may the force be with you";

  mstrncat(s, t, n);
  printf("mstrncat: %s\n", s);

  n = 5;
  t = "hello";

  printf("mstrcmp: %d\n", mstrncmp(s, t, n));
  free(s);

  return 0;
}

void mstrncpy(char *s, char *t, int n) {
  for (; n > 0 && (*s++ = *t++) != 0; n--)
    ;
}

void mstrncat(char *s, char *t, int n) {
  for (s += strlen(s); n > 0 && (*s++ = *t++) != 0; n--)
    ;
}

int mstrncmp(char *s, char *t, int n) {
  for (; n > 0 && *t != 0; s++, t++, n--) {
    if (*s != *t)
      return *s - *t;
  }

  return 0;
}