Getc c – getc C Library Function

Getc c: 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

Getc in c: 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 using getc function

c getc: 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.

getc C Library 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);
}

Output

getc C Standard Library

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

getc C Library Function 1

#include<stdio.h>
 
int main(){
   char c;
 
   printf("Enter a character\n");
   c = getc(stdin);
   printf("Character entered: %c", c);
    
   return(0);
}

Output

Enter a character
A
Character entered: A