读取文本文件并将其内容打印到C中的屏幕

cad*_*ddy 2 c file-io

我正在编写一个函数来读取给定的文件并将其内容打印到屏幕上.目前我有以下内容:

int textdump(const char *filename)
{
  int n = 0;
  char ch;
  FILE *fileHandle;
  fileHandle = fopen(filename, "r");
  if ((fileHandle = fopen(filename, "r")) == NULL)
  {
    return -1;
    fclose(fileHandle);
  }
  while ((ch = fgetc(fileHandle) != EOF) )
  {
    printf("%c", ch);
    n++;
  }

  fclose(fileHandle);
  if (fclose(fileHandle) == EOF)
  {
    return EXIT_FAILURE;
  }
  return n;
}
Run Code Online (Sandbox Code Playgroud)

该函数成功读取文本文件并正确返回每个文件中的字符数.但后来我试图打印字符,现在我甚至无法运行程序 - 我得到"运行失败 - doc不能为null,无法解析测试结果".

Sou*_*osh 6

总结上述代码的问题,

  • 在你的代码,你为什么fopen()/ fclose()-ing两次?摆脱那部分.---------------(1)
  • 你不需要fclose()那些尚未打开的东西.----------------------------------------------(2)
  • 之后的所有陈述return都没有效果.-------------------------------------------------- ----(3)
  • 使用时注意运算符优先级fgetc().-----------------------------------------(4)
  • fgetc()返回int值.相应地改变.-----------------------------------------------(5)

所以,你的代码看起来像

int textdump(const char *filename)
{
int n = 0;
int ch = 0;
FILE *fileHandle = NULL;
//fileHandle = fopen(filename, "r");  //not reqd  --- (1)
    if ((fileHandle = fopen(filename, "r")) == NULL){
    return -1;
    //fclose(fileHandle); // not reqd  --- (2), (3)
}
while ( (ch = fgetc(fileHandle)) != EOF ){   //notice here   -- (4), (5)
  printf("%c", ch);
  n++;
}

fclose(fileHandle);
/*
if(fclose(fileHandle) == EOF){ -- (1)
    return EXIT_FAILURE;
 }*/
 return n;
 }
Run Code Online (Sandbox Code Playgroud)

  • @EliasVanOotegem:不,他不是.第一个电话被注释掉了. (3认同)