Latest web development tutorials

C 庫函數– fgetc()

C 標準庫 - <stdio.h> C標準庫- <stdio.h>

描述

C庫函數int fgetc(FILE *stream)從指定的流stream獲取下一個字符(一個無符號字符),並把位置標識符往前移動。

聲明

下面是fgetc() 函數的聲明。

int fgetc(FILE *stream)

參數

  • stream --這是指向FILE對象的指針,該FILE對象標識了要在上面執行操作的流。

返回值

該函數以無符號char 強制轉換為int 的形式返回讀取的字符,如果到達文件末尾或發生讀錯誤,則返回EOF。

實例

下面的實例演示了fgetc() 函數的用法。

#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);
}

假設我們有一個文本文件file.txt ,它的內容如下。 文件將作為實例中的輸入:

We are in 2014

讓我們編譯並運行上面的程序,這將產生以下結果:

We are in 2014

C 標準庫 - <stdio.h> C標準庫- <stdio.h>