Skip to content

Instantly share code, notes, and snippets.

@FernandoBasso
Last active December 31, 2016 11:18
Show Gist options
  • Save FernandoBasso/e6cc59eb853ee9ee67463990fca7239a to your computer and use it in GitHub Desktop.
Save FernandoBasso/e6cc59eb853ee9ee67463990fca7239a to your computer and use it in GitHub Desktop.
The C Programming Language, exercise 1-20 (DETAB input).
// 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. Should n be a variable or a symbolic
// parameter?
// $ gcc -std=c99 -Wall -pedantic -L./lib -o devel devel.c -lmyline
// $ LD_LIBRARY_PATH=./lib ./devel <<< $'Li\tnu\tx\t\t!'
// len 39, line Li--------nu--------x----------------!
#include <stdio.h>
#include "lib/line.h"
#define MAXLEN 200 // Max input length allowed.
#define TABSIZE 8 // 8 spaces for each tab size.
int detab(char line[], int len);
int main(void)
{
int len;
char line[MAXLEN];
while ((len = get_line(line, MAXLEN)) > 0) {
len = detab(line, len);
fprintf(stdout, "len %d, line %s", len, line);
}
return 0;
}
int detab(char line[], int len)
{
int i, j;
int pos_dst;
int pos_src;
i = 0;
while (line[i] != '\0') {
if (line[i] == '\t') {
pos_dst = len + TABSIZE - 1;
j = len;
while (j > i) {
pos_src = j;
//printf("len %d, j %d, pos_src %d, pos_dst %d\n", len, j, pos_src, pos_dst);
line[pos_dst] = line[pos_src];
--pos_dst;
--j;
}
while (pos_dst >= i) {
line[pos_dst] = '-';
--pos_dst;
}
len += TABSIZE - 1;
}
++i;
}
return len;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment