所以我试着写一个函数来读取文本文件中的行数。但是,我注意到即使在超过文本文件行数时,函数也不会退出。为什么?为什么我把它

fgets(sentence, 70, inputFile);

柜台前++
int GetNumLine(char *fileName){

    FILE *inputFile;

    //counter are used to store number of lines
    int counter = 0;

    char sentence [70];

    inputFile = fopen(fileName,"r");

    //if there are anything wrong with inputfile
    if(inputFile == NULL){
        printf("Error while opening file");
        exit(1);
    }


    while(!feof(inputFile) ){


        counter++;
    }

    fclose(inputFile);

    return counter;
}

最佳答案

这永远是真的

while(!feof(inputFile))

您需要从文件中读取才能到达结尾并设置EOF标记,我建议您这样做
int chr;
while ((chr = fgetc(inputFile)) != EOF)
    counter += (chr == '\n') ? 1 : 0;

当您将fgets()置于从文件读取的counter++之前并更改FILE *结构中的位置时,当您试图读取到文件末尾之后时,EOF将被设置并且feof(inputFile)将返回非零。
带有fgets()字符的代码可以工作,但并不健壮,因为您可以有一行的字符数超过69字符,它将被计数两次,根据我的建议,结果总是正确的。

07-24 09:46
查看更多