9p / who / tweedy / 9C / 1


Exercise 1.18: Remove Trailing Blanks

Code

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

#define STDIN   0
#define MAXLINE 1000    /* maximum input line size */

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

/* remove trailing blanks and tabs; delete blank lines */
void
main()
{
    int len;        /* current line length */
    char line[MAXLINE]; /* current input line */
    int i, j;

    Biobuf *bstdin;
    bstdin = Bfdopen(STDIN, OREAD);

    for(i = 0; (len = getline(bstdin, line, MAXLINE)) > 0; ++i){
        for(j = len-1; line[j]==' ' || line[j]=='\t' || line[j]=='\n'; j--)
            line[j] = '\0';
        print("%s", line);
    }

    exits(0);
}

/* getline: read a line into s, return length */
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 trim.c; 9l trim.o -o trim
$ ./trim < trim.c
#include <u.h>#include <libc.h>#include <bio.h>#define  STDIN   0#define    MAXLINE 1000    /* maximum input line size */#define LEN    80  /* we will print lines longer than this length */int getline(Biobuf *buffer, char line[], int maxline);void copy(char to[], char from[]);/* remove trailing blanks and tabs; delete blank lines */voidmain(){   int len;        /* current line length */   char line[MAXLINE]; /* current input line */    int i, j;   Biobuf *bstdin; bstdin = Bfdopen(STDIN, OREAD); for(i = 0; (len = getline(bstdin, line, MAXLINE)) > 0; ++i){        for(j = len; line[j]=='\0' || line[j]==' ' || line[j]=='\t' || line[j]=='\n'; j--)          line[j] = '\0';     print("%s", line);  }   exits(0);}/* getline: read a line into s, return length */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
$ nano trim.c
$ 9c trim.c; 9l trim.o -o trim
$ ./trim < TEXT
text followed by three tabstext followed by three spaces$ 

TEXT

text followed by three tabs         
text followed by three spaces   




tweedy