Continuing my K&R journey!
Please see below for my solution to:
Exercise 1-20: Write a program detab that replaces tabs in the input with the proper number of blanks to space to the next tab stop. Assume a fixed set of tab stops, say every n columns.
#include <stdio.h>
#define TAB '\t' // character to look for
#define SPACE '-' // tab replacement char
#define TABSIZE 8 // fixed set of tab stops
#define MAXLINE 8000 // maximum number of chars in a line
static int getLine(char line[]);
static void processLine(char line[], int lineCharCount);
int main() {
int len; //length of line
char line[BUFSIZ]; //string constant array for appending ch
while ((len = getLine(line)) > 0) {
processLine(line, len);
}
return 0;
}
static int getLine(char line[]) {
int c;
int i;
for (i = 0; i < MAXLINE - 1 && (c = getchar()) != EOF && c != '\n'; ++i) {
line[i] = c;
}
if (c == '\n') {
line[i] = c;
++i;
}
line[i] = '\0';
return i;
}
static void processLine(char line[], int lineCharCount) {
int nonTabCount; // running count of characters up until \t is encountered
int i; // for loop
nonTabCount = 0;
for (i = 0; i < lineCharCount; i++) {
if (line[i] == TAB) {
nonTabCount++;
line[i] = SPACE;
putchar(line[i]);
while (TABSIZE - nonTabCount > 0) {
putchar(SPACE);
nonTabCount++;
}
nonTabCount = 0;
} else {
putchar(line[i]);
nonTabCount++;
if (nonTabCount >= TABSIZE) {
nonTabCount = 0;
}
}
}
}