深入ungetc函数探究

发布时间:2023-05-20

一、ungetc函数

ungetc函数是C语言标准库函数中的一员,其功能是将一个字符退回到流stdin的缓冲区中去,以便于下一次读取。 其原型如下:

int ungetc(int c, FILE *stream);

其中,参数c是将要被退回到缓冲区的字符,参数stream表示字符流,通常情况下设置为stdin或文件指针。

二、ungetc函数的用法

ungetc函数通常与getc、getchar等函数一起使用,可以用来改变输入流中字符的读取顺序。 当从stdin读取到一个字符,但是发现该字符并不是自己所需要的,可以使用ungetc函数将其退回到缓冲区后再使用getc等函数重新读取。这样可以方便地实现有条件的字符读取。 同时,ungetc函数的返回值表示是否成功退回,如果成功,则返回退回的字符,否则返回EOF。

三、ungetch的功能

ungetch是ungetc函数的一种变形,它将字符退回到输入缓冲区中,可以用来实现更为复杂的输入逻辑。 在不同的操作系统上,输入缓冲区的大小可能会有所不同,ungetch可以将字符放回到缓冲区队列的最前端,因此对于连续输入的字符,可以实现较为灵活的控制。 以下是ungetch函数的示例代码:

#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int ungetch(int c) {
    if (bufp >= BUFSIZE) {
        printf("ungetch: too many characters\n");
        return 0;
    }
    buf[bufp++] = c;
    return c;
}

四、ungetchar

ungetchar是将一个字符退回到输入流中的简单函数,与ungetc函数类似,但是只能将1个字符退回到输入流中。 以下是ungetchar函数的示例代码:

int ungetchar(int c) {
    return ungetc(c,stdin);
}

五、ungetc函数的用法例子

下面是一个简单的例子,演示了ungetc函数的用法。

#include <stdio.h>
int main() {
    int c;
    while ((c = getchar()) != EOF) {
        if (c == '/') {
            if ((c = getchar()) == '/') {
                while ((c = getchar()) != '\n')
                    ;
                continue;
            } else if (c == '*') {
                while ((c = getchar()) != EOF) {
                    if (c == '*') {
                        if ((c = getchar()) == '/') {
                            break;
                        } else {
                            ungetc(c, stdin);
                        }
                    }
                }
                continue;
            } else {
                ungetc(c, stdin);
            }
        }
        putchar(c);
    }
    return 0;
}

以上代码实现的是一个简单的注释过滤程序,可以过滤掉C语言中的注释内容。其中,ungetc函数用于在判断不是注释语法的时候将读取到的字符放回输入流,以便后续的读取。