问题描述
所以我想把我拥有的文件的行数作为函数的参数,但我不知道为什么这个循环无限期地运行。
int count_numbers(FILE *filea) {
int i;
while (!feof(filea)) {
i++;
}
fclose(filea);
i--;
return i;
}
解决方法
您的函数根本不计算行数,并且存在多个问题:
-
i
未初始化 while (!feof(filea))
is always wrong- 您不测试读取的字节是否为换行符
- 关闭文件应该是调用者的责任
这是修改后的版本:
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;
}
,
循环中的任何内容都不能改变文件的 EOF 标志。循环中的所有内容都是 i++;
,它不会导致遇到文件结尾。因此,如果循环一次,循环将无限次循环。