如何查找文件的行数?

fri*_*nds 2 c file

例如:

file_ptr=fopen(“data_1.txt”, “r”);
Run Code Online (Sandbox Code Playgroud)

我如何找到文件中的行数?

pax*_*blo 9

您读取文件中的每个字符并添加换行符.

您应该考虑fgetc()阅读一个字符,并记住它将EOF在文件末尾返回并返回\n行尾字符.

然后你只需要决定最后一条不完整的行(即文件末尾没有换行符)是否为一行.我会说是的,我自己.

这是我如何做到的,当然是伪代码,因为这是作业:

open file
set line count to 0
read character from file
while character is not end-of-file:
    if character in newline:
        add 1 to line count
    read character from file
Run Code Online (Sandbox Code Playgroud)

在这个级别的问题中,可能不需要扩展它以处理不完整的最后一行.如果(或者你想尝试额外的学分),你可以看看:

open file
set line count to 0
set last character to end-of-file
read character from file
while character is not end-of-file:
    if character in newline:
        add 1 to line count
    set last character to character
    read character from file
if last character is not new-line:
    add 1 to line count
Run Code Online (Sandbox Code Playgroud)

不能保证其中任何一个都能起作用,因为它们只是我的头脑,但如果他们不这样做我会感到惊讶(但这不是我见过的第一个或最后一个惊喜 - 测试它好).