getc : <stdio.h> library function

The function int getc(FILE *stream); returns a single character from the given stream. It increments the position indicator of the file to point to next character. If the stream is at the end-of-file when called, the function returns EOF and sets the end-of-file indicator for the stream.

Function prototype of getc

int getc(FILE *stream);
  • stream : A pointer to a FILE object which identifies a stream.

Return value of getc

This function returns the character read from the stream (type casted to an int value) otherwise returns EOF in case of error or If end of file is reached.

C program to show the use of getc function

The following program shows the use of getc function to read the content of a file. It first writes "getc C Standard Library function" string in a text file called textFile.txt then reads the content of this file character by character using getc function.

#include <stdio.h>
#include <string.h>

int main (){
   FILE *file;
   char *string = "getc C Standard Library function";
   int c;

   file = fopen("textFile.txt", "w+");
   /* Writing string to a file(stream) */
   fputs(string, file);
   /* Reset file pointer location to first character */
   rewind(file);
   /* Read characters from file */
   while(!feof(file)){
      c = getc(file);
      printf("%c", c);
   }
   fclose(file);
   
   return(0);
}

Program Output
getc C Standard Library

The following program shows the use of getc function to read characters standard input stream(keyboard).

#include<stdio.h>

int main(){
   char c;

   printf("Enter a character\n");
   c = getc(stdin);
   printf("Character entered: %c", c);
   
   return(0);
}

Program Output
Enter a character
A
Character entered: A