9p / who / tweedy / 9C / 1


Exercise 1.20: Detab

Note: The process of rendering .c files into html for these web pages already necessarily detabs them, so the effect of this program can’t be seen here. See the original program file instead.

Code

#include <u.h>
#include <libc.h>
#include <bio.h>

#define STDIN   0
#define TABSTOP 5
#define MAXLINE 1000

int getline(Biobuf *buffer, char line[], int maxline);

/* replace tabs in the input with the proper number of blanks to space to the next tab stop */
void
main()
{
    char line[MAXLINE];
    int len, i, j, k;
    Biobuf *bstdin;
    bstdin = Bfdopen(STDIN, OREAD);

    while((len = getline(bstdin, line, MAXLINE)) > 0){
        for(i = 0, j = 0; i <= len; ++i){
            if(line[i] != '\t'){
                print("%c", line[i]);
                ++j;
            }
            else{
                int l = TABSTOP - (j % TABSTOP);
                for(k = 0; k < l; ++k){
                    print(" ");
                    ++j;
                }
            }
        }
    }
}

int getline(Biobuf *b, char s[], int lim)
{
    int c, i;

    for(i = 0; i<lim-1 && (c=Bgetc(b))>= 0 && c!='\n'; ++i)
        s[i] = c;
    if(c == '\n'){
        s[i] = c;
        ++i;
    }
    s[i] = '\0';
    return i;
}

Output

$ 9c detab.c; 9l detab.o -o detab
$ ./detab < detab.c
#include <u.h>
#include <libc.h>
#include <bio.h>

#define   STDIN     0
#define   TABSTOP   5
#define   MAXLINE   1000

int getline(Biobuf *buffer, char line[], int maxline);

/* replace tabs in the input with the proper number of blanks to space to the next tab stop */
void
main()
{
     char line[MAXLINE];
     int len, i, j, k;
     Biobuf *bstdin;
     bstdin = Bfdopen(STDIN, OREAD);

     while((len = getline(bstdin, line, MAXLINE)) > 0){
          for(i = 0, j = 0; i <= len; ++i){
               if(line[i] != '\t'){
                    print("%c", line[i]);
                    ++j;
               }
               else{
                    int l = TABSTOP - (j % TABSTOP);
                    for(k = 0; k < l; ++k){
                         print(" ");
                         ++j;
                    }
               }
          }
     }
}

int getline(Biobuf *b, char s[], int lim)
{
     int c, i;

     for(i = 0; i<lim-1 && (c=Bgetc(b))>= 0 && c!='\n'; ++i)
          s[i] = c;
     if(c == '\n'){
          s[i] = c;
          ++i;
     }
     s[i] = '\0';
     return i;
}



tweedy