Page 118
Modify the programs entab
and detab
(written as exercises in Chapter 1) to accept
a list of tab stops as arguments. Use the default tab settings if there are no
arguments.
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#define MAXLINE 1000
#define DEFAULT_TAB_STOP 4
int main(int argc, char *argv[])
{
int c, i, tab_pos = 0;
char line[MAXLINE];
unsigned tab_stop = DEFAULT_TAB_STOP;
if (argc > 1) {
for (i = 0; isdigit(argv[1][i]); i++)
;
if (argv[1][i] != '\0') {
printf("First argument must be an integer!\n");
return 1;
}
tab_stop = atoi(argv[1]);
}
while ((c = getchar()) != EOF) {
if (c == '\t') {
for (int i = 0; i < (tab_stop - tab_pos); i++) {
putchar(' ');
}
tab_pos = 0;
} else {
putchar(c);
if (c == '\n') {
tab_pos = 0;
} else {
tab_pos++;
tab_pos %= tab_stop;
}
}
}
}