C File I/O Operations : getc()

The getc() function is used to reads a single character from file. It gets a single character at a time from the input stream. It returns the value of character read, or in case of any error, or at end of file it returns EOF. The basic syntax for getc() is :
 int getc(FILE *fp);
Where fp is file pointer. In programming, it is implemented like this :
FILE *fp;
char ch;
fp = fopen("myfile.txt", "r");
while((ch=getc(fp)) != EOF) {
  printf("%c", ch);
}
The above code read character from myfile.txt and prints it as output. The first three lines are self-explanatory, after that a while loop is used, where the loop continues until getc() returned value is not EOF. Now lets look at C example code :
#include <stdio.h>

int main() {

  FILE *fp;
  char ch;
  fp = fopen("myfile.txt", "r");

  while((ch=getc(fp)) != EOF) {
    printf("%c", ch);
  }

  fclose(fp);
  return 0;
}
Output :

Hello world, This is Sample Text.

Note : Create a file myfile.txt, before running the above program, otherwise it does not show anything as output.

Topics :