行数比预期少两行

编程语言 2026-07-10
    // Last task removal
    if(!strcmp(argv[2], "last")) {
        int line = 0; // Which line is last in the file

        FILE *fileptr = fopen(FileAddress, "r"); // Create file pointer and open it in read and write

        char* filebuffer = calloc(10000, sizeof(uint8_t)); // Create memory on the heap

        while(fgetc(fileptr) != EOF) { // Loop through the file until end of file
            if (fgetc(fileptr) == 10) { // Check if its a new line
                line++; // Increment line count
            }

        }

        printf("%d", line);


    }

这段代码本应返回一个简单文本文件中有多少行,但不知为何,每次运行返回的行数总是比预期少2。我已经试着自己修正过,但怎么也想不通。

另外,是的,我知道这段代码可能不太好,但这是我在做一个猜数字游戏之后的第二个C 语言项目。肯定有更好的实现方式,我也在努力,请多点理解 :(

解决方案

OP在每次循环中读取两个字符

改为每次循环只读取一个字符。

        int ch; // Add
        // while(fgetc(fileptr) != EOF) { // Loop through the file until end of file
        while((ch = fgetc(fileptr)) != EOF) { // Loop through the file until end of file
            // if (fgetc(fileptr) == 10) { // Check if its a new line
            if (ch == '\n') { // Check if its a new line
                line++; // Increment line count
            }
        }

最后一行缺少一个结尾的 '\n'

一个常见的原因是,文件的最后一行缺少一个 '\n'。因此,与其统计 '\n' 的出现次数,不如统计行首的数量。

int prior_char = '\n';
int ch;
while((ch = fgetc(fileptr)) != EOF) { // Loop through the file until end of file
  if (prior_char == '\n') { // Check if start of a new line.
    line++; // Increment line count
  }
  prior_char = ch;
}
  • 高级:考虑为行数使用比 int 更宽的类型,因为对一个文件的行数而言,确实没有上限,使用 unsigned long long 几乎不会对性能造成影响。32位的 int 现在看起来很大,但二十年后会不会也显得很“大”?换句话说,请为未来做打算。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章