
- C 标准库
- C 库 - 首页
- C 库 - <assert.h>
- C 库 - <complex.h>
- C 库 - <ctype.h>
- C 库 - <errno.h>
- C 库 - <fenv.h>
- C 库 - <float.h>
- C 库 - <inttypes.h>
- C 库 - <iso646.h>
- C 库 - <limits.h>
- C 库 - <locale.h>
- C 库 - <math.h>
- C 库 - <setjmp.h>
- C 库 - <signal.h>
- C 库 - <stdalign.h>
- C 库 - <stdarg.h>
- C 库 - <stdbool.h>
- C 库 - <stddef.h>
- C 库 - <stdio.h>
- C 库 - <stdlib.h>
- C 库 - <string.h>
- C 库 - <tgmath.h>
- C 库 - <time.h>
- C 库 - <wctype.h>
- C 标准库资源
- C 库 - 快速指南
- C 库 - 有用资源
- C 库 - 讨论
C 库 - ungetc() 函数
C 库函数 int ungetc(int char, FILE *stream) 将字符 char(一个无符号字符)压回指定流中,以便下次读取操作可以使用它。这在需要将字符放回输入流的场景中非常有用,通常是在读取字符并确定它不是当时要处理的正确字符之后。
语法
以下是 C 库函数 ungetc() 的语法:
int ungetc(int char, FILE *stream);
参数
此函数接受以下参数:
- char : 要压回流中的字符。它被转换为无符号字符。
- stream : 指向 FILE 对象的指针,标识该流。
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
返回值
成功时,ungetc 函数返回压回流中的字符。如果发生错误,函数返回 EOF 并设置流的错误指示符。
示例 1:ungetc 的基本用法
程序从文件中读取第一个字符,使用 ungetc 将其压回流中,然后再次读取它以演示它已成功压回。
以下是 C 库函数 ungetc() 的示例。
#include <stdio.h> int main() { FILE *file = fopen("example1.txt", "r"); if (file == NULL) { perror("Unable to open file"); return 1; } int c = fgetc(file); printf("Read character: %c\n", c); ungetc(c, file); int c2 = fgetc(file); printf("Read character again: %c\n", c2); fclose(file); return 0; }
输出
上述代码产生以下结果:
Read character: H Read character again: H
示例 2:处理多个 ungetc 调用
在此示例中,多次调用 ungetc 以演示如何处理压回多个字符。
#include <stdio.h> int main() { FILE *file = fopen("example3.txt", "r"); if (file == NULL) { perror("Unable to open file"); return 1; } int c1 = fgetc(file); int c2 = fgetc(file); printf("Read characters: %c%c\n", c1, c2); ungetc(c2, file); ungetc(c1, file); printf("Pushed back characters: %c%c\n", c1, c2); int d1 = fgetc(file); int d2 = fgetc(file); printf("Read characters again: %c%c\n", d1, d2); fclose(file); return 0; }
输出
执行上述代码后,我们将得到以下结果:
Read characters: H Pushed back characters: He Read characters again: He
广告