Skip to content

Instantly share code, notes, and snippets.

@meikj
Created August 3, 2013 18:17
Show Gist options
  • Save meikj/6147427 to your computer and use it in GitHub Desktop.
Save meikj/6147427 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#define DEFAULT_TAB_STOP 4
#define DEFAULT_REPLACE ' ' // used as tab replacement
int main(int argc, char *argv[]) {
char *arg_end;
int c, tab_stop, curr_col, spaces;
curr_col = 1; // denotes the current column
if (argc < 2) {
tab_stop = DEFAULT_TAB_STOP;
} else {
tab_stop = (int)strtol(argv[1], &arg_end, 10);
if(*arg_end) {
fprintf(stderr, "error: invalid argument: %s\n", arg_end);
exit(1);
} else if(tab_stop > 8) {
fprintf(stderr, "error: tab stop size too big: %d\n", tab_stop);
exit(1);
}
}
while ((c = getchar()) != EOF) {
if (c == '\n') {
// reset tab stop
printf("\n");
curr_col = 1;
} else if(c == '\t') {
if(curr_col % tab_stop == 0) {
// we're at the tab stop, so just print one space
printf("%c", DEFAULT_REPLACE);
curr_col++;
} else {
// get number of spaces until next tab stop
spaces = (tab_stop - (curr_col % tab_stop)) + 1;
curr_col += spaces;
for (; spaces > 0; spaces--)
printf("%c", DEFAULT_REPLACE);
}
} else {
printf("%c", c);
curr_col++;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment