當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 ungetc()用法及代碼示例


描述

C庫函數int ungetc(int char, FILE *stream)推動角色char (an unsigned char)到指定的stream以便此可用於下一個讀取操作。

聲明

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

int ungetc(int char, FILE *stream)

參數

  • char- 這是要放回的字符。這作為它的 int 提升傳遞。

  • stream- 這是指向標識輸入流的 FILE 對象的指針。

返回值

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

示例

下麵的例子展示了 ungetc() 函數的用法。

#include <stdio.h>

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

   fp = fopen("file.txt", "r");
   if( fp == NULL ) {
      perror("Error in opening file");
      return(-1);
   }
   while(!feof(fp)) {
      c = getc (fp);
      /* replace ! with + */
      if( c == '!' ) {
         ungetc ('+', fp);
      } else {
         ungetc(c, fp);
      }
      fgets(buffer, 255, fp);
      fputs(buffer, stdout);
   }
   return(0);
}

讓我們假設,我們有一個文本文件file.txt,其中包含以下數據。該文件將用作我們示例程序的輸入 -

this is tutorials point
!c standard library
!library functions and macros

現在,讓我們編譯並運行上麵的程序,將產生以下結果 -

this is tutorials point
+c standard library
+library functions and macros

相關用法


注:本文由純淨天空篩選整理自 C library function - ungetc()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。