为什么多了一个“?” C程序执行后显示(读取并显示一个txt文件)

Why is there an extra "?" displayed after executing C program(to read aand display a txt file)

我写了一个 C 程序,它读取现有的 txt 文件并输出该文件中的内容。

我遇到的问题是它在末尾显示 ?

例如:如果文件(txt)中的内容为Hello World!,则终端显示Hello World!?.

代码如下:

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

int main()
{
    FILE * fp;
    char ch;
    char filename[100];
    char filename2[100];

    printf("Enter the file you want to display(without .txt): \n");
    scanf("%s", filename);
    sprintf(filename2, "%s.txt", filename);
    /* opens the file in read mode */
    fp = fopen(filename2, "r");

    /* NULL if last operation was unsuccessful */
    if(fp == NULL)
    {
        printf("Unable to open file.\n");
        exit(1);
    }
    printf("File opened successfully. \n\n");
    while (ch != EOF)
    {
        /* Read single character from file */
        ch = fgetc(fp);
        /* Print character */
        putchar(ch);
    }
    fclose(fp);
    return 0;
}

在尝试使用“读取”之前,您必须检查读取是否成功

还有fgetc()returnsint,所以变量ch应该是int,否则会很难区分其中一个是有效的带有 EOF 的字符。

    for (;;)
    {
        /* Read single character from file */
        ch = fgetc(fp);

        /* Check if something is actually read */
        if (ch == EOF) break;

        /* Print character */
        putchar(ch);
      }

只需将文件内容复制到另一个文件,然后杀死该文件。 再试一次。 有时它会因为垃圾值而发生。

否则,一旦读取文件就使用此代码。

fflush(stdin);
fflush(stdout);

如果这不起作用,请在代码中的其他一些适当位置使用它们。 有时它发生是因为输入和输出缓冲区。