9p / who / tweedy / 9C / 1


Exercise 1.16: Longest Line (accept long input)

Code

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

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

int getline(Biobuf *buffer, char line[], int maxline);
void copy(char to[], char from[]);

/* print length of longest line and as much as possible of the text; accept arbitrarily long input */
void
main()
{
    int len;        /* current line length */
    int prevlen;        /* previous line length */
    int max;        /* maximum length so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE];  /* longest line saved here */

    Biobuf *bstdin;
    bstdin = Bfdopen(STDIN, OREAD);
    prevlen = max = 0;

    while((len = getline(bstdin, line, MAXLINE)) > 0){
        if(line[len-1] == '\n'){
            if(prevlen > 0){
                len += prevlen;
            }
            if(len > max) {
                max = len;
                if(prevlen == 0)
                    copy(longest, line);
            }
            prevlen = 0;
        }
        else{
            len += prevlen;
            if(len > max) {
                max = len;
                copy(longest, line);
            }
            prevlen = len;
        }
    }
    if(max > 0){
        print("%d\n", max);
        if(max > MAXLINE)
            print("Here is some of the longest line:\n");
        print("%s", longest);
        if(longest[max%(MAXLINE-1) - 1] != '\n')
            print("\n");
    }

    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;
}

/* copy: copy 'from' into 'to'; assume to is big enough */
void copy(char to[], char from[])
{
    int i;

    i = 0;
    while((to[i] = from[i]) != '\0')
        ++i;
}

Output

$ 9c longest+.c; 9l longest+.o -o longest+
$ ./longest+ < longest+.c
102
Here is some of the longest line:
/* print length of longest line and as much as possible of the text; accept arb



tweedy