C getc macro : C Reference



getc macro : Read Character from Stream (stdio.h Header file)

  1. getc is a macro.
  2. getc accepts one character from a stream
  3. Header file : Stdio.h
  4. getc returns the next character on the given input stream .
  5. Getc increments the stream’s file pointer to point to the next character.
  6. getc returns the character read, after converting it to an int without sign extension.

Syntax :

int getc(FILE *stream);

Live Example :

int main(void) 
{
char ch;
printf("\nInput a character:");

/* read a character from the standard
   input stream */

ch = getc(stdin);

printf("\nThe character input was : '%c'", ch);

return 0;
}

Output :

Input a character : P
The character input was : 'P'

Another Live Example :

#include<stdio.h>
int main()
{
  int ch;
  FILE *fp;
  if (fp = fopen("file.txt", "rt"))
  {
    ch = getc(fp);
    while (ch != EOF)
    {
      printf("%c", ch);
      ch = getc(fp);
    }
    fclose(fp);
  }
  return 0;
}

Output :

It will read complete file till we get EOF