summaryrefslogtreecommitdiffstats
path: root/3/2.c
blob: f6f6987da10d4e103a7c6acda44a789e3bb38cc4 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
#include <stdio.h>
#include <string.h>

#define ESCAPE 0
#define UNESCAPE 1
#define MAXLEN 1000

/* convert new line and tab chars to visible chars */
void escape(char s[], char t[]);

/* converts escapes sequences to chars */
void unescape(char s[], char t[]);

int main(int argc, char *argv[]) {
  int c, i, cmd;
  char s[MAXLEN], t[MAXLEN];

  if (!strcmp(argv[1], "e"))
    cmd = ESCAPE;
  else if (!strcmp(argv[1], "u"))
    cmd = UNESCAPE;
  else
    return 1;

  printf("Enter string to %s and press Ctrl+D\n",
         cmd == ESCAPE ? "escape" : "unescape");

  for (i = 0; i < MAXLEN - 1 && (c = getchar()) != EOF; i++)
    t[i] = c;
  t[i] = 0;

  if (cmd == ESCAPE) {
    escape(s, t);
    printf("Escaped output:\n");
    printf("%s\n", s);
  } else if (cmd == UNESCAPE) {
    unescape(s, t);
    printf("Unescaped output:\n");
    printf("%s\n", s);
  } else {
    return 1;
  }

  return 0;
}

void escape(char s[], char t[]) {
  int c, i, j;

  for (i = 0, j = 0; (c = t[i]) != 0; i++) {
    switch (c) {
    case '\n': {
      s[j++] = '\\';
      s[j++] = 'n';
      break;
    }
    case '\t': {
      s[j++] = '\\';
      s[j++] = 't';
      break;
    }
    default:
      s[j++] = c;
    }

    s[j] = 0;
  }
}

void unescape(char s[], char t[]) {
  int c, i, j;

  for (i = 0, j = 0; (c = t[i]) != 0; i++) {
    if (j > 0 && s[j - 1] == '\\') {
      switch (c) {
      case 'n':
        s[j - 1] = '\n';
        break;
      case 't':
        s[j - 1] = '\t';
        break;
      default:
        s[j++] = c;
      }
    } else {
      s[j++] = c;
    }
  }

  s[j] = 0;
}