exc/k&r/01-a-tutorial-introduction/01-20-detab.c

49 lines
968 B
C

#include <stdio.h>
#include <stdlib.h>
#define TABSTOP 4
void detab(int tabstop);
int fill(int indent, int tabstop);
/* detab input, takes one optional argument for tabstop width */
int main(int argc, char *argv[])
{
int tabstop;
if (argc < 2 || !(tabstop = atoi(argv[1])))
detab(TABSTOP);
else
detab(tabstop);
return 0;
}
/* detabs input with spaces, tab stop width is 'tabstop' */
void detab(int tabstop)
{
int c, indent = 0; /* indent starts at 0 */
while ((c = getchar()) != EOF)
if (c == '\t')
indent = fill(indent, tabstop);
else {
putchar(c);
indent = (c == '\n') ? 0 : indent + 1;
}
}
/* fills output with spaces from indent to next tabstop */
/* returns new indent */
int fill(int indent, int tabstop)
{
int w = tabstop - indent % tabstop;
for (; w > 0; --w) {
putchar(' ');
++indent;
}
return indent;
}