ckernighan-and-ritchie

Why doesn't this while loop go on forever? Beginner C question


#define MAXLINE 1000
char pattern[] = "ould";
main()
{
    char line[MAXLINE];
    int found = 0;

    while (getline(line,MAXLINE) > 0)
       if (strindex(line, pattern) >= 0 ) {
          printf("%s", line);
          found ++;
       }
    return found
}

Why does that while loop go on forever? getline(line,1000) would, as I barely understand it, return the length of the line, and "append it" (?) to MAXLINE, making a number larger than 1000, depending on the line length... why would that ever dip below zero?

I read that getline returns -1 if "unsuccessful", when would that be? When would line not be read?

This is on page 69 of Kernighan. I've been skipping around the book, and I'm currently backtracking to see where I missed something.

"Describe what you tried, what you expected to happen, and what actually resulted. Minimum 20 characters."


Solution

  • I'm assuming you are using the getline and strindex defined in the book:

    /* getline: get line into s, return length */
    int getline(char s[], int lim)
    {
        int c, i;
    
        i = 0;
        while (--lim > 0 && (c=getchar()) != EOF && c != '\n')
            s[i++] = c;
        if (c == '\n')
            s[i++] = c;
        s[i] = '\0';
        return i;
    }
    
    /* strindex: return index of t in s, -1 if none */
    int strindex(char s[], char t[])
    {
        int i, j, k;
    
        for (i = 0; s[i] != '\0'; i++) {
            for (j=i, k=0; t[k] != '\0' && s[j] == t[k]; j++, k++)
                ;
            if (k > 0 && t[k] == '\0')
                return i;
        }
        return -1;
    }
    

    As you can see getline reads until it reaches end of file(EOF). If you are running the program on the command-line, your program is waiting for this signal from standard in, you can send this signal manually by pressing Control-d.

    if you cat a file into the program:

    $ cat test.txt | ./your program
    

    the end of file value it sent, at the end of the file.