fgetc 打印错误的字符到控制台

fgetc prints wrong characters to console

我的程序应该打印文本文件中包含的文本,该文本文件保存在与源代码和可执行文件相同的目录中,然后打印行数。 但是,输出是一些随机字符。 我正在使用 ubuntu.

跟进问题:哪个必须与文件(如果我不指定绝对路径)、可执行文件或源代码位于同一目录中? 提前致谢。

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

int main(){
  char c;
  int i = 0;

  FILE *fp = fopen("newfile","r"); 
  if(!fp) {
    printf("Error opening\n");
    return -1;
  }

  printf("Text of newfile: \n");
  while(fgetc(fp)!=EOF){
    c = fgetc(fp);
    printf("%c",c);

    if(c == '\n')
      ++i;
  }

  fclose(fp);
  fp = NULL;
  printf("\nThere are %d lines in the file\n",i+1);

  return 0;
}

文件包含文本:

this is my file
this is line 2

输出:

Text of newfile: 
hsi yfl
hsi ie2�
There are 2 lines in the file

对于初学者,您在循环中使用了两次 fgetc

  while(fgetc(fp)!=EOF){
        ^^^^^^^^^ 
    c = fgetc(fp);
        ^^^^^^^^^
    //...  

其次,变量 c 必须声明为类型 int

循环可以如下所示

int c;

//...

while ( ( c = fgetc( fp ) ) != EOF )
{
    putchar( c );
    if ( c == '\n' ) ++i;
}