【问题标题】:Identifying newline characters in a file using C使用 C 识别文件中的换行符
【发布时间】:2016-06-07 17:39:58
【问题描述】:

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

.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

【问题讨论】:

  • 您在每个循环中调用了两次fgetc。所以你打印/检查替代字符。
  • 注意:不需要将ch复制到char类型的变量中,因为'\n'无论如何都是int类型。
  • 哦排序。谢谢! @Vane

标签: c file file-io fgetc


【解决方案1】:

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

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

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

【讨论】:

  • 是的,我意识到了。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-03-05
  • 2015-11-12
  • 2015-04-06
  • 2011-03-02
  • 1970-01-01
  • 2015-09-28
  • 1970-01-01
  • 2021-02-12
相关资源
最近更新 更多