我们有一个程序,它将一个文件作为输入,然后计算该文件中的行数,但不计算空行数。
Stack Overflow 中已经有一篇关于这个问题的帖子,但这个问题的答案并没有涵盖我。
我们举一个简单的例子。
文件:
I am John\n
I am 22 years old\n
I live in England\n
Run Code Online (Sandbox Code Playgroud)
如果最后一个 '\n' 不存在,那么计数会很容易。我们实际上已经有一个函数可以做到这一点:
/* Reads a file and returns the number of lines in this file. */
uint32_t countLines(FILE *file) {
uint32_t lines = 0;
int32_t c;
while (EOF != (c = fgetc(file))) {
if (c == '\n') {
++lines;
}
}
/* Reset the file pointer to the start of the file */
rewind(file);
return lines;
}
Run Code Online (Sandbox Code Playgroud)
这个函数,当把上面的文件作为输入时,计算了 4 行。但我只想要 3 行。
我试图以多种方式解决这个问题。
首先,我尝试fgets在每一行中执行并将该行与字符串“\0”进行比较。如果一行只是“\0”而没有其他内容,那么我认为这可以解决问题。
我也尝试了其他一些解决方案,但我真的找不到任何解决方案。
我基本上想要的是检查文件中的最后一个字符(不包括'\0')并检查它是否是'\n'。如果是,则从它先前计数的行数中减去 1(使用原始函数)。我真的不知道如何做到这一点。有没有其他更简单的方法来做到这一点?
我将不胜感激任何类型的帮助。谢谢。
小智 5
您实际上可以通过仅跟踪最后一个字符来非常有效地修改此问题。
这是有效的,因为空行具有前一个字符必须是\n.
/* Reads a file and returns the number of lines in this file. */
uint32_t countLines(FILE *file) {
uint32_t lines = 0;
int32_t c;
int32_t last = '\n';
while (EOF != (c = fgetc(file))) {
if (c == '\n' && last != '\n') {
++lines;
}
last = c;
}
/* Reset the file pointer to the start of the file */
rewind(file);
return lines;
}
Run Code Online (Sandbox Code Playgroud)