A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.tutorialspoint.com/c_standard_library/c_function_ungetc.htm below:

C Library - ungetc() function

C Library - ungetc() function

The C library int ungetc(int char, FILE *stream) function pushes the character char (an unsigned char) onto the specified stream so that the this is available for the next read operation. This can be useful in scenarios where you need to put a character back into the input stream, often after reading it and determining it was not the right character to process at that time.

Syntax

Following is the C library syntax of the ungetc() function −

int ungetc(int char, FILE *stream);
Parameters

This function accepts the following parameters −

Return Value

On success, the ungetc function returns the character pushed back onto the stream. If an error occurs, the function returns EOF and sets the error indicator for the stream.

Example 1: Basic Usage of ungetc

The program reads the first character from the file, pushes it back onto the stream with ungetc, and then reads it again to demonstrate that it was successfully pushed back.

Below is the illustration of the C library ungetc() function.

#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;
}
Output

The above code produces following result−

Read character: H
Read character again: H
Example 2: Handling Multiple ungetc Calls

In this example, multiple calls to ungetc are made to demonstrate how pushing back multiple characters can be handled.

#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;
}
Output

After execution of above code, we get the following result

Read characters: H
Pushed back characters: He
Read characters again: He

RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4