Easy Tutorial
❮ C Examples Reverse Number C Function Printf ❯

C Library Function - fgetc()

C Standard Library - <stdio.h>

Description

The C library function int fgetc(FILE *stream) gets the next character (an unsigned char) from the specified stream and advances the position indicator for the stream.

Declaration

Here is the declaration for the fgetc() function.

int fgetc(FILE *stream)

Parameters

Return Value

This function returns the character read as an unsigned char cast to an int, or EOF if the end of the file is reached or if a reading error occurs.

Example

The following example demonstrates the use of the fgetc() function.

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;
   int n = 0;

   fp = fopen("file.txt","r");
   if(fp == NULL) 
   {
      perror("Error opening file");
      return(-1);
   }
   do
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }while(1);

   fclose(fp);
   return(0);
}

Assume we have a text file file.txt, which contains the following content. The file will serve as input for the example:

We are in 2014

Let's compile and run the above program, which will produce the following result:

We are in 2014

C Standard Library - <stdio.h>

❮ C Examples Reverse Number C Function Printf ❯