C Library Functions -fgetc()

C Standard Library - <stdio.h>

Description

C Library Functionsint fgetc(FILE *stream)Gets the next character (an unsigned char) from the specified stream and advances the position indicator.

Declaration

Below is the declaration of the fgetc() function.

int fgetc(FILE *stream)

Parameter

  • stream-- This is a pointer to a FILE object that identifies the stream on which the operation is to be performed.

Return Value

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

Example

The following example demonstrates the usage 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("打开文件时发生错误");
      return(-1);
   }
   do
   {
      c = fgetc(fp);
      if( feof(fp) )
      {
          break ;
      }
      printf("%c", c);
   }while(1);

   fclose(fp);
   return(0);
}

Suppose we have a text filefile.txt, whose content is as follows. The file will be used as input in the example:

We are in 2014

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

We are in 2014

C Standard Library - <stdio.h>

other extensions