ungetc() – C语言库函数
C语言库函数 int ungetc(int char, FILE *stream) 将字符的字符(unsigned char类型)到指定的流,用于下一个读操作。
声明
以下是声明 ungetc() 函数。
int ungetc(intchar, FILE *stream)
参数
-
char -- 这是被放回到字符。这是通过作为整型转换。
-
stream -- 这是一个文件对象的指针,识别输入流。
返回值
如果成功,则返回字符推回,否则,返回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 yiibai !c standard library !library functions and macros
让我们编译和运行上面的程序,这将产生以下结果:
this is tutorials yiibai +c standard library +library functions and macros +library functions and macros