I am trying to do a few exercises from the K&R book from the first chapter - exercise 1-19. I have to write a program "detab" which replaces tabs in the input with the proper number of blanks to the next tab stop. Assume a fixed set of tab stops, say every n position.
Here is what I've written so far (My Solution):
#include <stdio.h>
#include <stdlib.h>
#define TAB '\t'
#define SPACE ' '
#define DEFTABSIZE 4 /* default tab size */
#define calc_n_spaces(x, y) ( (y - (x % y)) )
void detab(const char *restrict);
int
main(void)
{
char *buf = NULL;
size_t bufsiz = 0;
while (getline(&buf, &bufsiz, stdin) != -1)
(void) detab(buf);
free(buf);
exit(EXIT_SUCCESS);
}
void
detab(const char *restrict from)
{
int i, j, spaces;
char to[BUFSIZ];
i = j = 0;
while ((to[i] = from[i]) != '\0') {
if (to[i] == TAB) {
spaces = calc_n_spaces(j, DEFTABSIZE); /* calculate number of spaces. */
while (spaces-- > 0) {
(void) putchar(SPACE);
++j;
}
} else {
(void) putchar(to[i]);
++j;
}
++i;
}
return;
}
I'd like to know if there is a way I can improve it.
Note: I am using the 1st version of the book.




