📜  C / C++中的ungetc()

📅  最后修改于: 2021-05-25 22:13:54             🧑  作者: Mango

ungetc()函数采用单个字符并将其推回到输入流中。它与getc()函数相反,后者从输入流中读取单个字符。另外,ungetc()是输入函数,而不是输出函数。
句法:

int ungetc(int char, FILE *stream)

参数:

  • char :指定要放回的字符的int提升。放回时,该值在内部转换为无符号字符。
  • stream :指定指向标识输入流的FILE对象的指针。

返回值:该函数返回两种值。

  • 成功时,ungetc()函数将返回字符ch。
  • 失败时,将返回EOF,而不更改流。

有关该函数的要点:

  1. ungetc()函数将char指定的字节(转换为无符号char)推回到stream指向的输入流上。
  2. 推回的字节由该流上的后续读取以推入的相反顺序返回。
  3. 对文件定位函数(fseek(),fsetpos()或rewind())的成功干预(流由流指向)将丢弃该流的所有推回字节。
  4. 与该流相对应的外部存储器应保持不变。
  5. 成功调用ungetc()会清除流的文件结束指示符。
  6. 在读取或丢弃所有推回的字节之后,流的文件位置指示符的值应与推回字节之前的值相同。
  7. 每次成功调用ungetc()都会减小文件位置指示符,如果在调用前其值是0,则在调用后未指定其值。

下面的程序说明了上述函数。

程序1:

#include 
  
int main()
{
    FILE* f;
    int char;
    char buffer[256];
  
    // read a file
    f = fopen("use1.txt", "r");
  
    // when no data
    if (f == NULL) {
        printf("Error in opening file");
        return (-1);
    }
  
    // read lines till end
    while (!feof(f)) {
  
        // get line
        char = getc(f);
        // replace ! with +
        if (char == '!') {
            ungetc('+', f);
        }
        // if not
        else {
            ungetc(c, f);
        }
        fgets(buffer, 255, f);
        fputs(buffer, stdout);
    }
    return 0;
}

假设我们有一个文本文件use1.txt,其中包含以下数据。该文件将用作示例程序的输入,然后输入和输出如下所示:

Input: !c standard library
       !library function stdio.h-ungetc()
Output: +c standard library
        +library function stdio.h-ungetc()

程式2:

// C program for taking input till we
// get 1 at the input 
#include 
int main()
{
    int ch;
  
    // reads characters from the stdin and show
    // them on stdout until encounters '1'
    while ((ch = getchar()) != '1')
        putchar(ch);
  
    // ungetc() returns '1' previously
    // read back to stdin
    ungetc(ch, stdin);
  
    // getchar() attempts to read
    // next character from stdin
    // and reads character '1' returned
    // back to the stdin by ungetc()
    ch = getchar();
  
    // putchar() displays character
    putchar(ch);
    return 0;
}
想要从精选的最佳视频中学习和练习问题,请查看《基础知识到高级C的C基础课程》。