C-standard-library-c-function-ungetc

提供:Dev Guides
移動先:案内検索

Cライブラリ関数-ungetc()

説明

Cライブラリ関数 int ungetc(int char、FILE stream)は、文字 char(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