exc/k&r/01-a-tutorial-introduction/01-21-entab.c

45 lines
957 B
C

#include <stdio.h>
#include <stdlib.h>
#define TABSTOP 4
void entab(int tabstop);
/* entab input, takes one optional argument for tabstop width */
int main(int argc, char *argv[])
{
int tabstop;
if (argc < 2 || !(tabstop = atoi(argv[1])))
entab(TABSTOP);
else
entab(tabstop);
return 0;
}
/* entabs input with spaces, tab stop width is 'tabstop' */
void entab(int tabstop)
{
int c, indent; /* indent starts at 1 */
int bn = 0; /* current number of blanks */
for (indent = 1; (c = getchar()) != EOF; ++indent)
if (c == ' ') {
if (indent % tabstop || bn == 0)
/* dont entab single spaces */
++bn;
else {
bn = 0;
putchar('\t');
}
} else {
for(; bn > 0; --bn)
putchar(' ');
putchar(c);
if (c == '\n')
indent = 0;
}
}