使用 C 识别文件中的换行符

Identifying newline characters in a file using C

我正在尝试读取文本文件中的换行符,从而计算文本文档中的行数

.txt 文件的内容:

我的
姓名

约翰

我的代码输出:

牛米
s

行号为 1

我的代码:

    #include <stdlib.h>
    #include <string.h>
    #include <stdio.h>


    int main()
    {

         FILE* filepointer ;
          filepointer = fopen("C:\Users\Summer Work\Let's C\Comnsole\TestFile.txt","rb+") ;

        int count = 0 ;
        int ch;
        printf("%c\n",ch) ;

          while ((ch = fgetc(filepointer)) != EOF)
          {
             printf("%c",ch) ;
             ch = fgetc(filepointer)  ;

            char dh = ch;
            if (dh == '\n')
            count++ ;
           }


         printf("\nLine number is %d",count) ;

         fclose(filepointer) ;
         getchar() ;
         return 0;
 }

有人能解释一下为什么会这样吗?

更新: 固定码

    #include <stdlib.h>
    #include <string.h>
#include <stdio.h>


int main()
{

   FILE* filepointer ;
filepointer = fopen("C:\Users\Summer Work\Let's C\Comnsole\TestFile.txt","rb+") ;

int count = 0 ;
int ch;


while ((ch = fgetc(filepointer)) != EOF)
{
    printf("%c",ch) ;
    if (ch == '\n')
        count++ ;

}


printf("\nLine number is %d",count) ;

fclose(filepointer) ;
getchar() ;
return 0;

}

输出

我的
姓名

约翰
行号为 3

您在 while 循环中执行了两次 fgetc。您也没有任何特殊原因将 ch 复制到 dh。我改进了您的代码,对其进行了测试并且它可以完美运行。给你:

      while ((ch = fgetc(filepointer)) != EOF)
      {
        printf("%c",ch);
        if (ch == '\n')
           count++;
      }

您还需要初始化 int ch = 0;,因为在它获得任何值之前打印它会导致未定义的行为。