2

I wrote a C program which reads an existing txt file and outputs the contents inside that file.

The issue I'm having is that it displays a ? at the end.

For example: if the contents in the file(txt) were Hello World!, the terminal displays Hello World!?.

Here is the code:

#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;
}
IrAM
  • 1,720
  • 5
  • 18

2 Answers2

1

You have to check if the reading is successful before trying to use what is "read".

Also fgetc() returns int, so the variable ch should be int, otherwise it will make it difficult to distinguish between one of valid characters with EOF.

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

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

        /* Print character */
        putchar(ch);
      }
MikeCAT
  • 73,922
  • 11
  • 45
  • 70
0

Just copy the file contents to another file, and kill the file . And try once again. Some time it happens because of the garbage value.

Otherwise just use this code once the file is read.

fflush(stdin);
fflush(stdout);

if that didn't work use these in some other appropriate places in the code. Sometime it happens because of the input and output buffer.

Dharman
  • 30,962
  • 25
  • 85
  • 135
krishnaacharyaa
  • 14,953
  • 4
  • 49
  • 88