-
Notifications
You must be signed in to change notification settings - Fork 0
/
high-ascii-to-escape-sequence.c
114 lines (95 loc) · 2.59 KB
/
high-ascii-to-escape-sequence.c
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <stdio.h>
#include <stdlib.h>
static void options(int argc, char *argv[]);
static inline void unable_to_write(void);
static FILE *in, *out;
int main(int argc, char *argv[]) {
options(argc, argv);
enum token {
N, NEWLINE = N,
D, DOUBLE = D,
S, SLASH = S,
H, HIGH = H,
A, ASTERISK = A,
C, CHAR = C,
MAX_TOKEN
};
enum effect {
PUT,
ESC
};
enum state {
CODE, /* code */
STRN, /* string */
MBCM, /* maybe comment */
CCOM, /* C comment */
MBCD, /* maybe code */
CPPC, /* C++ comment */
MAX_STATE
};
struct transition {
enum state next;
enum effect effect;
};
struct transition table[MAX_STATE][MAX_TOKEN] = {
/* NEWLINE, DOUBLE, SLASH, HIGH, ASTERISK, CHAR */
[CODE] = { [N]={CODE,PUT}, [D]={STRN,PUT}, [S]={MBCM,PUT}, [H]={CODE,ESC}, [A]={CODE,PUT}, [C]={CODE,PUT} },
[STRN] = { [N]={STRN,PUT}, [D]={CODE,PUT}, [S]={STRN,PUT}, [H]={STRN,ESC}, [A]={STRN,PUT}, [C]={STRN,PUT} },
[MBCM] = { [N]={CODE,PUT}, [D]={CODE,PUT}, [S]={CPPC,PUT}, [H]={CODE,PUT}, [A]={CCOM,PUT}, [C]={CODE,PUT} },
[CCOM] = { [N]={CCOM,PUT}, [D]={CCOM,PUT}, [S]={CCOM,PUT}, [H]={CCOM,PUT}, [A]={MBCD,PUT}, [C]={CCOM,PUT} },
[MBCD] = { [N]={CCOM,PUT}, [D]={CCOM,PUT}, [S]={CODE,PUT}, [H]={CCOM,PUT}, [A]={CCOM,PUT}, [C]={CCOM,PUT} },
[CPPC] = { [N]={CODE,PUT}, [D]={CPPC,PUT}, [S]={CPPC,PUT}, [H]={CPPC,PUT}, [A]={CPPC,PUT}, [C]={CPPC,PUT} }
};
int c;
struct transition transition = {CODE, PUT};
while (c = getc(in), c != EOF) {
enum token token;
switch (c) {
case '*': token = ASTERISK; break;
case '"': token = DOUBLE; break;
case '/': token = SLASH; break;
case '\n': token = NEWLINE; break;
default: token = (c & 128) ? HIGH : CHAR; break;
}
transition = table[transition.next][token];
switch (transition.effect) {
case PUT:
if (EOF == putc(c, out))
unable_to_write();
break;
case ESC:
if (4 > fprintf(out, "\\%o", (unsigned char) c))
unable_to_write();
break;
}
}
if (ferror(in)) {
perror("Unable to read from source file");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
static void options(int argc, char *argv[]) {
if (argc == 1) {
in = stdin;
out = stdout;
return;
}
if (argc != 3) {
fprintf(stderr, "Expected either 0 or 2 arguments.\n");
exit(EXIT_FAILURE);
}
if (!(in = fopen(argv[1], "r"))) {
perror(argv[1]);
exit(EXIT_FAILURE);
}
if (!(out = fopen(argv[2], "w"))) {
perror(argv[2]);
exit(EXIT_FAILURE);
}
return;
}
static inline void unable_to_write(void) {
perror("Unable to write to destination file");
exit(EXIT_FAILURE);
}