C programming stdio.h function - int ungetc(int char, FILE *stream)

‮igi.www‬ftidea.com

The ungetc function in the stdio.h library of the C programming language is used to push a character back into a specified stream, so that it becomes the next character to be read from the stream. The syntax of the ungetc function is as follows:

int ungetc(int char, FILE *stream);

Here, the first argument char is the character to be pushed back into the stream, and the second argument stream is a pointer to the FILE structure that represents the stream.

The ungetc function pushes the specified character back into the stream, so that it becomes the next character to be read from the stream. The function returns the character pushed back on success. In case of an error, it returns EOF. The EOF macro is a constant defined in the stdio.h library that represents the end-of-file condition or an error condition.

For example, the following code reads a character from the standard input stream, pushes it back into the stream using the ungetc function, and then reads the character again:

#include <stdio.h>

int main() {
   int ch;
   ch = getchar();
   if (ch == EOF) {
      printf("Error reading from stream\n");
      return 1;
   }
   ungetc(ch, stdin);
   ch = getchar();
   if (ch == EOF) {
      printf("Error reading from stream\n");
      return 1;
   }
   printf("Character read: %c\n", ch);
   return 0;
}

In this example, the getchar function reads a character from the standard input stream. If the read operation is successful, the character is stored in the ch variable. The ungetc function then pushes the character back into the stream, so that it becomes the next character to be read from the stream. The getchar function is then called again, and it reads the character pushed back into the stream. Finally, the program prints the character read using the printf function.