检索文件中的总行数

ase*_*sel 5 c text file

有人能告诉我如何用编程语言C获取文本文件中的总行数吗?

Ara*_*raK 21

这是一种方法:

FILE* myfile = fopen("test.txt", "r");
int ch, number_of_lines = 0;

do 
{
    ch = fgetc(myfile);
    if(ch == '\n')
        number_of_lines++;
} while (ch != EOF);

// last line doesn't end with a new line!
// but there has to be a line at least before the last line
if(ch != '\n' && number_of_lines != 0) 
    number_of_lines++;

fclose(myfile);

printf("number of lines in test.txt = %d", number_of_lines);
Run Code Online (Sandbox Code Playgroud)

  • 这个函数给出了错误的结果,因为循环退出`ch!= EOF`然后`ch`的值用`ch!='\n''测试,这总是正确的,因为此时`ch`等于'EOF`.如果文件以`\n`字符结尾,则该函数错误地返回另一行.如果文件为空或者它不以`\n`结尾,则该函数返回预期的行数.一个正确的解决方案将检查`EOF`之前的最后一个字符. (2认同)