Search code examples
cfile-iofopentextinputgetch

Reading text file in C


My professor gave us the code to get input from a text file. The issue is it will not compile properly for me. I'm not sure where he (or I) went wrong. I have not modified his code in any way and my txt file is in the same directory as the code.

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


int main()
{
     FILE *fp;
     char ch;
     fp = fopen("IronHeelShort.txt", "r");
     printf("Data inside file : ");
     while(1)
     {
         ch = fgetc(fp);
         printf("%c", ch);
         if (ch == EOF)
         break;

     }
     getch();
}

Solution

  • chshould be an int anyway The function fgetc() will always return an int, to handle all the char values and EOF which is negative. Here reading your file will prematurely end when finding character 0xFF.

    For the compiling issue, change getch() into getchar()