C++ Standard Library C++ STL Library

C++ <cstdio> - getc() Function



The C++ <cstdio> getc() function returns the character currently pointed by the internal file position indicator of the specified stream and advances the position indicator to the 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 feof(). If a read error occurs, the function returns EOF and sets the error indicator for the stream ferror().

getc() and fgetc() are equivalent, except that getc() may be implemented as a macro in some libraries.

Syntax

int getc ( FILE * stream );

Parameters

stream Specify a pointer to a FILE object that specifies an input stream.

Return Value

  • On success, the character read is returned.
  • If the failure has been caused due to end-of-file condition, returns EOF and sets the end-of-file indicator for the stream feof().
  • If a read error occurs, the function returns EOF and sets the error indicator for the stream ferror().

Example:

Lets assume that we have a file called test.txt. This file contains following content:

This is a test file.
It contains dummy content.

In the example below, file is opened using fopen() function. If the return value of calling getc() function is not EOF, it starts reading characters the file one by one and writes the characters to output stream.

#include <stdio.h>
 
int main (){
  //open the file in read mode
  FILE *pFile = fopen("test.txt", "r");
  
  //first character in the file
  int c = getc(pFile);
  
  //if first character is not EOF, reads and writes
  //characters from the file until EOF is reached
  while (c != EOF) {
    putchar(c);
    c = getc(pFile);
  }
  
  //close the file
  fclose(pFile);
  return 0;
}

The output of the above code will be:

This is a test file.
It contains dummy content.

❮ C++ <cstdio> Library