-1

So I want to count the lines of the file I have as the argument of the function, but I don't know why does this loop run indefinitely.

int count_numbers(FILE *filea) {
    int i;
    while (!feof(filea)) {
        i++;
    }
    fclose(filea);
    i--;
    return i;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
sawaszef
  • 15
  • 1
  • `feof` doesn't take in anything new. If the file descriptor wasn't already marked as being at the end of file, it won't suddenly be EOF in the loop. – Thomas Jager Mar 08 '21 at 20:58
  • See [Why is `while(!feof(fp))` always wrong?](https://stackoverflow.com/questions/5431941) – user3386109 Mar 08 '21 at 21:16
  • 2
    Why hasn't this been closed as a duplicate in under two minutes? [Why is “while ( !feof (file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feof-file-always-wrong) – Marco Bonelli Mar 08 '21 at 22:11

2 Answers2

3

Your function does not count the lines at all and it has multiple problems:

Here is a modified version:

int count_lines(FILE *filea) {
    int c;
    int last = '\n';
    int lines = 0;

    while ((c = getc(filea)) != EOF) {
        if (c == '\n')
            lines++;
        last = c;
    }
    if (last != '\n') {
        // last line does not have a trailing newline, adjust the count
        lines++;
    }
    return lines;
}
chqrlie
  • 131,814
  • 10
  • 121
  • 189
0

Nothing in the loop can possibly change the file's EOF flag. All that's in the loop is i++; which cannot cause the end of the file to be encountered. So the loop will loop an infinite number of times if it loops once.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278
  • Meta-question about your answer: I noticed you started with one-sentence answer and then started updating it to fill out the sentence with more detail. I also notice you have a really high reputation and probably know a thing about getting reputation on SO. I wonder: is the idea to get something in with as early a timestamp as possible to dissuade other answerers from starting a response, or is there another reason to iterate from a stub answer like this? – user1717828 Mar 08 '21 at 21:02
  • @user1717828: This question is likely to be closed very quickly. David might have tried and succeeded at posting an answer before this... But I am only guessing. – chqrlie Mar 08 '21 at 21:12
  • @user1717828 I think it's a combination of two things. Part of it is that I always think of something I should have said right after it's too late but I think another is having the painful experience of composing a long, thoughtful answer to a good question only to have the question closed or deleted. Also, a close as a duplicate often doesn't help the OP while an answer that's "mostly" a duplicate does. – David Schwartz Mar 08 '21 at 21:24