C Programming/stdio.h/getc

From Wikibooks, open books for an open world
Jump to: navigation, search

getc is one of the character input functions. getc reads the next character from a file, it takes a file pointer to the file. It is the simplest function to read a file.

Like getchar, getc() may be implemented macro instead of function. getc is equivalent to fgetc. getc returns the next character from the stream referred to by fp; it returns EOF for End Of File or error.


int getc( FILE * stream);

Here, parameter stream is the pointer to a FILE object which identify the stream on which the operation is to be performed.


/*getc example*/

#include <stdio.h>
int main()
FILE *fp;
int c;
int n = 0;
fp = fopen("myfile.txt", "r");
  if(fp == NULL)
     perror ("Error opening file");
     do  {
         c = getc(fp);
         if(c == '#')
     while(c != EOF);
  printf ("File contains %d#.\n",n);
 return 0;

Above program read the file called myfile.txt character by character and uses n variable to count '#' character contained in file.

Return Value[edit]

Character read is returned as an int value.

If the End-of-File is reached or error in reading occurs, function returns EOF and corresponding error indicator. We can use either ferror or feof to determine whether an error happened or EOF reached.


External Links[edit]