C 库 - ungetc() 函数



C 库函数 int ungetc(int char, FILE *stream) 将字符 char(一个无符号字符)压回指定流中,以便下次读取操作可以使用它。这在需要将字符放回输入流的场景中非常有用,通常是在读取字符并确定它不是当时要处理的正确字符之后。

语法

以下是 C 库函数 ungetc() 的语法:

int ungetc(int char, FILE *stream);

参数

此函数接受以下参数:

  • char : 要压回流中的字符。它被转换为无符号字符。
  • stream : 指向 FILE 对象的指针,标识该流。

返回值

成功时,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
广告
© . All rights reserved.