Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C library function - fgetc()

C library function - fgetc()

C Standard Library - <stdio.h> C Standard Library -

Description

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

Declaration

The following is the declaration of the fgetc() function.



int fgetc(FILE *stream)

Parameters

Return Value

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

Example

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



#include 



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 file file.txt, whose content is as follows. The file will be used as input in 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 Standard Library -