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