Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created October 29, 2009 03:45
Show Gist options
  • Save shaobin0604/221118 to your computer and use it in GitHub Desktop.
Save shaobin0604/221118 to your computer and use it in GitHub Desktop.
tcpl_ex-1-20.c
/*
* 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?
*/
#include <stdio.h>
#define MAXLEN 1000
#define TABLEN 8
#define TAB '\t'
#define NL '\n'
#define SPACE ' '
int getline(char line[], int limit);
void replacetab(char from[]);
int main(void)
{
char line[MAXLEN];
while (getline(line, MAXLEN) > 0)
{
replacetab(line);
}
return 0;
}
int getline(char line[], int limit)
{
int i, j, c;
for (i = j = 0; (c = getchar()) != EOF && c != NL; j++)
{
if (i < limit - 2)
{
line[i++] = c;
}
}
if (c == NL)
{
line[i++] = NL;
j++;
}
line[i] = '\0';
return j;
}
void replacetab(char from[])
{
int i, j, c, pos, offset;
for (i = pos = 0; (c = from[i]) != '\0'; i++)
{
if (c == TAB)
{
offset = pos;
for (j = 0; j < TABLEN - (offset % TABLEN); j++)
{
putchar(SPACE);
pos++;
}
}
else
{
putchar(c);
pos++;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment