目录

int ungetc(int char, FILE *stream)

描述 (Description)

C库函数int ungetc(int char, FILE *stream)将字符char (an unsigned char)推送到指定的stream以便下次读取操作可用。

声明 (Declaration)

以下是ungetc()函数的声明。

int ungetc(int char, FILE *stream)

参数 (Parameters)

  • char - 这是要放回的角色。 这是作为int推广传递的。

  • stream - 这是指向标识输入流的FILE对象的指针。

返回值 (Return Value)

如果成功,则返回被推回的字符,否则返回EOF并且流保持不变。

例子 (Example)

以下示例显示了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
↑回到顶部↑
WIKI教程 @2018