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

Reading a text file and printing its contents to the screen in C

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

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;
}

函数成功读取文本文件,returns正确读取每个文件中的字符数。但是后来我尝试打印字符,现在我什至无法 运行 程序 - 我得到 "Failed to run - doc cannot be null, can't parse test results".

while ( (ch = fgetc(fileHandle) != EOF) )

应该是

while ( (ch = fgetc(fileHandle)) != EOF)

您需要注意运算符的优先级。使用发布的代码 ch = fgetc() 将不会像您认为的那样首先被评估,因此添加括号以确保您将它们绑定在一起,如上所示。

总结上述代码的问题,

  • 在您的代码中,为什么要 fopen()/ fclose()-ing 两次?摆脱那部分。 --------------(1)
  • 您不需要fclose() 尚未打开的内容。 ----------------------------------------------(2)
  • return之后的所有语句均无效。 ---------------------------------------------- ----(3)
  • 在使用 fgetc() 时注意 operator precedence。 --------------------------------------(4)
  • fgetc() returns 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;
 }
int textdump(const char *filename)
{
    int n = 0;
    FILE *fileHandle;
    /* char ch; fgetc wants an int (able to store EOF) not a char */
    int ch;
    fileHandle = fopen(filename, "r");
    if (fileHandle == NULL){
        /* return -1; */ 
        /* fclose(fileHandle); */
        /* you can not close what is not oppened */
        perror("fopen");
        return -1;
    }
    while ((ch = fgetc(fileHandle)) != EOF) /* Beware of the precedence */
        printf("%c", ch);
        n++;
    }
    /* You don't need to check the result of fclose
    if(fclose(fileHandle) == EOF){ 
    return EXIT_FAILURE;
    }
    */
    fclose(fileHandle);
    return n;
}

这应该够了

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