0

I have been trying to create a function to count the number of lines of code. This is what I have come up with, but it is getting stuck in an infinite loop.

int numberoflines(char filename[]){
    FILE *file = fopen(filename, "r");
    int count = 0;
    int ch = 0;
    while( EOF != (ch = getchar())){
        if(ch == '\n'){
            count++;
        }
    }
    return count;
}
Jeromy Irvine
  • 11,614
  • 3
  • 39
  • 52
  • 2
    How come `getchar()` would magically know which file you expect it to read from? –  Dec 31 '12 at 07:01

2 Answers2

9

It's not an infinite loop, it's just that you aren't reading from the file you opened, but from standard input. Try getc(file) instead of getchar().

Dolda2000
  • 25,216
  • 4
  • 51
  • 92
  • 3
    I would also suggest that OP look at http://stackoverflow.com/questions/1835986/how-to-use-eof-to-run-through-a-text-file-in-c – Neo Dec 31 '12 at 05:56
  • Question gives a clear idea about the usage and return values of various file I/O functions. Just thought it will be helpful. – Neo Dec 31 '12 at 06:00
3

It's not in an infinite loop, it's reading from standard input, probably the terminal, because you used getchar() instead of getc(file).

You should also fclose(file) before you return.

DigitalRoss
  • 143,651
  • 25
  • 248
  • 329