-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathentab_v0.c
102 lines (97 loc) · 2.12 KB
/
entab_v0.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
/* Exercise 5-12. Extend entab and detab to accept the shorthand
* entab -m +n
* to mean tab stops every n columns, starting at column m. Choose convenient
* (for the user) default behavior. */
#include "stdio.h"
#include "stdlib.h"
#define RB '#' // for replacing of blank
#define RT '@' // for replacing of tab
int main(int argc, char *argv[]) {
unsigned char sc = 0; // starting column, index starts at 0
unsigned char ts = 4; // tab stop
char status;
const char *usage = "usage: entab OPTIONS\n"
"OPTIONS:\n"
"-m\n\ttab starts at column m\n"
"-n\n\ttab stops every n column\n";
int bep, p, nb, nt, c;
enum STATUS {IN, OUT};
while (--argc) {
switch (**++argv) {
case '-':
sc = atoi(++*argv);
break;
case '+':
ts = atoi(++*argv);
break;
default:
printf("error: invalid arguments\n%s", usage);
return 0;
}
}
bep = 0; // blank entrance position
p = -sc - 1; // current position in a line
nb = 0; // the number of blanks
nt = 0; // the number of tabs
status = OUT; // outside blank block
while ((c = getchar()) != EOF) {
if (p >= 0)
switch (status) {
case IN:
switch (c) {
case ' ':
break;
case '\t':
p += ts - 1;
break;
case '\n':
putchar('\n');
nb = 0;
nt = 0;
p = -sc - 2;
status = OUT;
break;
default: // non-blank
bep -= bep % ts;
nb = (p - bep) % ts;
nt = (p - bep) / ts;
while (nt--)
putchar(RT);
while (nb--)
putchar(RB);
nt = 0;
nb = 0;
putchar(c);
status = OUT;
break;
}
break;
case OUT:
switch (c) {
case ' ':
bep = p;
status = IN;
break;
case '\t':
bep = p;
p += ts - 1;
status = IN;
break;
case '\n':
putchar('\n');
p = -sc - 2;
break;
default:
putchar(c);
break;
}
break;
default:
break;
}
else
putchar(c);
++p;
}
return 0;
}