ungetcungetwc

将字符重新推送到流上。

语法

int ungetc(
   int c,
   FILE *stream
);
wint_t ungetwc(
   wint_t c,
   FILE *stream
);

参数

c
要推送的字符。

stream
指向 FILE 结构的指针。

返回值

如果成功,则其中每个函数都会返回字符自变量 c。 如果无法推送回 c 或未读取任何字符,则输入流不改变且 ungetc 返回 EOFungetwc 返回 WEOF。 如果 streamNULL,则会调用无效的参数处理程序,如参数验证中所述。 如果允许执行继续,则返回 EOFWEOF并将 errno 设置为 EINVAL

有关这些错误代码和其他错误代码的信息,请参阅 errno_doserrno_sys_errlist_sys_nerr

注解

ungetc 函数将字符 c 重新推送到 stream 上,并清除文件结尾指示符。 流必须打开以供读取。 stream 上的后续读取操作以 c 开始。 将忽略尝试使用 ungetcEOF 重新推送到流上。

如果从流中读取此字符前调用了 fflushfseekfsetpos、或 rewind,则可能会消除 ungetc 在流上放置的字符。 文件位置指示符将拥有将字符推送回之前的值。 对应流的外部存储未改变。 对文本流的 ungetc 调用成功后,将不指定文件位置指示符,直至读取或弃用推送回的所有字符。 每次对二进制流的 ungetc 调用成功后,文件位置指示符将减少;如果调用前其值为 0,则调用后不定义此值。

如果调用了 ungetc 两次且在两次调用之间没有读取或文件定位操作,则结果不可预知。 调用 fscanf 后,除非已执行其他读取操作(例如 getc),否则对 ungetc 的调用可能会失败,因为 fscanf 本身会调用 ungetc

ungetwcungetc 的宽字符版本。 但是,每次对文本或二进制流的 ungetwc 调用成功后,将不指定文件位置指示符的值,直至读取或弃用推送回的所有字符。

这些函数线程安全并会在执行期间锁定敏感数据。 有关非锁定版本,请参阅 _ungetc_nolock_ungetwc_nolock

默认情况下,此函数的全局状态范围限定为应用程序。 若要更改此行为,请参阅 CRT 中的全局状态

一般文本例程映射

TCHAR.H 例程 _UNICODE_MBCS 未定义 _MBCS 已定义 _UNICODE 已定义
_ungettc ungetc ungetc ungetwc

要求

例程 必需的标头
ungetc <stdio.h>
ungetwc <stdio.h> 或 <wchar.h>

通用 Windows 平台 (UWP) 应用中不支持控制台。 与控制台、stdinstdoutstderr 关联的标准流句柄必须重定向,然后 C 运行时函数才能在 UWP 应用中使用它们。 有关兼容性的详细信息,请参阅 兼容性

示例

// crt_ungetc.c
// This program first converts a character
// representation of an unsigned integer to an integer. If
// the program encounters a character that is not a digit,
// the program uses ungetc to replace it in the  stream.
//

#include <stdio.h>
#include <ctype.h>

int main( void )
{
   int ch;
   int result = 0;

   // Read in and convert number:
   while( ((ch = getchar()) != EOF) && isdigit( ch ) )
      result = result * 10 + ch - '0';    // Use digit.
   if( ch != EOF )
      ungetc( ch, stdin );                // Put nondigit back.
   printf( "Number = %d\nNext character in stream = '%c'",
            result, getchar() );
}

      521aNumber = 521
Next character in stream = 'a'

另请参阅

流 I/O
getcgetwc
putcputwc