9p / who / tweedy / 9C / 1


Exercise 1.17: Print Lines Longer than 80 Characters

Code

#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 */

/* make sure we have at least one line in the program that is longer than 80 characters to test */

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

/* print all lines longer than 80 characters (bonus: with line number) */
void
main()
{
    int len;        /* current line length */
    char line[MAXLINE]; /* current input line */
    int i;          /* current line number */

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

    for(i = 0; (len = getline(bstdin, line, MAXLINE)) > 0; ++i)
        if(len > LEN)
            print("%d: %s", i, 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 80.c; 9l 80.o -o 80
$ ./80 < 80.c
8: /* make sure we have at least one line in the program that is longer than 80 characters to test */



tweedy