From c80f4af866508cf2812ba030bf7abfb70d126b6e Mon Sep 17 00:00:00 2001 From: Zhineng Li Date: Fri, 29 May 2026 11:52:36 +0800 Subject: ch01-21: replace blanks by proper tabs --- ch01/ex21-entab.c | 89 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 ch01/ex21-entab.c (limited to 'ch01/ex21-entab.c') diff --git a/ch01/ex21-entab.c b/ch01/ex21-entab.c new file mode 100644 index 0000000..1282c61 --- /dev/null +++ b/ch01/ex21-entab.c @@ -0,0 +1,89 @@ +#include + +#define TABSTOP 8 /* number of columns between tab stops */ +#define DEBUG 0 /* display tabs and spaces explicitly */ + +#define SYM_SP '.' /* visible space for debugging */ +#define SYM_TAB '~' /* visible tab for debugging */ + +void puttab(void); +void putspace(int len); + + +/* replace blanks by proper tabs */ +int main() +{ + int c; /* current character */ + int offset; /* position inside current tab stop */ + int nspace; /* number of spaces */ + + if (DEBUG) { + printf("# debug mode is on\n"); + printf("# displaying spaces and tabs explicitly\n"); + printf("# space -> %c\n", SYM_SP); + printf("# tab -> %c\n", SYM_TAB); + } + + offset = nspace = 0; + while ((c = getchar()) != EOF) { + ++offset; + + if (c == ' ') + ++nspace; + else if (c == '\t') { + puttab(); + offset = nspace = 0; + } else if (nspace) { + putspace(nspace); + nspace = 0; + } + + if (offset == TABSTOP) { + if (nspace) + puttab(); + offset = nspace = 0; + } + + if (c == '\n') { + if (nspace) + putspace(nspace); + offset = nspace = 0; + } + + if (c != ' ' && c != '\t') + putchar(c); + } + + if (nspace) + putspace(nspace); + + return 0; +} + +/* print a tab */ +void puttab(void) +{ + int c; + + if (DEBUG) + c = SYM_TAB; + else + c = '\t'; + + putchar(c); +} + +/* print len spaces */ +void putspace(int len) +{ + int i; + int c; + + if (DEBUG) + c = SYM_SP; + else + c = ' '; + + for (i = 0; i < len; ++i) + putchar(c); +} -- cgit v1.2.3