试图计算代码中的行数,但在C中陷入无限循环

0 c

我一直在尝试创建一个函数来计算代码行数.这就是我想出来的,但却陷入了无限循环.

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;
}
Run Code Online (Sandbox Code Playgroud)

Dol*_*000 9

它不是一个无限循环,只是你不是从你打开的文件中读取,而是从标准输入中读取.尝试getc(file)而不是getchar().

  • 我还建议OP查看http://stackoverflow.com/questions/1835986/how-to-use-eof-to-run-through-a-text-file-in-c (3认同)