Page 118
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>
#include <ctype.h>
#define DEFAULT_TAB_STOP 4
#define DEFAULT_INITIAL_COL 0
int main(int argc, char *argv[])
{
unsigned tab_stop = DEFAULT_TAB_STOP;
unsigned initial_col = DEFAULT_INITIAL_COL;
int val;
while (--argc > 0) {
if (isdigit(argv[argc][1])) {
val = atoi(argv[argc] + 1);
switch (argv[argc][0]) {
case '-':
initial_col = val;
break;
case '+':
tab_stop = val;
break;
}
}
}
int c, i, j;
int tab_pos = 0, nb = 0;
for (i = 0; (c = getchar()) != EOF; i++) {
++tab_pos;
tab_pos %= tab_stop;
if (c == ' ' && i >= initial_col) {
nb++;
if (tab_pos == 0) {
if (nb > 1) {
putchar('\t');
} else {
putchar(' ');
}
nb = 0;
}
} else {
for (j = 0; j < nb; j++) {
putchar(' ');
}
nb = 0;
if (c == '\n') {
tab_pos = 0;
i = 0;
}
putchar(c);
}
}
}