C 庫函數 - ungetc()

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

描述

C 庫函數 int ungetc(int char, FILE *stream) 把字元 char(一個無符號字元)推入到指定的流 stream 中,以便它是下一個被讀取到的字元。

聲明

下麵是 ungetc() 函數的聲明。

int ungetc(int char, FILE *stream)

參數

  • char -- 這是要被推入的字元。該字元以其對應的 int 值進行傳遞。
  • stream -- 這是指向 FILE 對象的指針,該 FILE 對象標識了輸入流。

返回值

如果成功,則返回被推入的字元,否則返回 EOF,且流 stream 保持不變。

實例

下麵的實例演示了 ungetc() 函數的用法。

#include <stdio.h>

int main ()
{
   FILE *fp;
   int c;
   char buffer [256];

   fp = fopen("file.txt", "r");
   if( fp == NULL )
   {
      perror("打開檔時發生錯誤");
      return(-1);
   }
   while(!feof(fp))
   {
      c = getc (fp);
      /* 把 ! 替換為 + */
      if( c == '!' )
      {
         ungetc ('+', fp);
      }
      else
      {
         ungetc(c, fp);
      }
      fgets(buffer, 255, fp);
      fputs(buffer, stdout);
   }
   return(0);
}

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

this is zaixian
!c standard library
!library functions and macros

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

this is zaixian
+c standard library
+library functions and macros
+library functions and macros

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