9p / who / tweedy / 9C / 1


Longest Line

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);
void copy(char to[], char from[]);

/* print longest line */
void
main()
{
    int len;        /* current line length */
    int max;        /* maximum length so far */
    char line[MAXLINE]; /* current input line */
    char longest[MAXLINE];  /* longest line saved here */

    /* we need to open the standard input buffer here in main() then pass it
       to getline(). If we open it in getline(), it'll be created new each
       time we call the function, so we'll only ever read in the first line. */
    Biobuf *bstdin;
    bstdin = Bfdopen(STDIN, OREAD);

    max = 0;
    while((len = getline(bstdin, line, MAXLINE)) > 0)
        if(len > max) {
            max = len;
            copy(longest, line);
        }
    if(max > 0) /* there was a line */
        print("%s", longest);

    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
    /* we need to open the standard input buffer here in main() then pass it



tweedy