Answer: We already have read from and written to individual characters from/to standard input/standard output and file I/O. The fact is that we can’t determine what character is on the stream until we have read it. Therefore we would read one character beyond the character we wanted. Then what about the extra character we have read to avoid losing it. That is, how can we return this character back to the stream? ‘ungetc()’ function is there to do the task. It’s syntax is as follows,
int ungetc(int ch, FILE * stream);
ungetc() returns previously read character back to the stream so that it could be read again. Let’s take a simple C program using capability of ungetc() below,
/* ungetc.c -- pushes a character back on the stream */ /* int ungetc(int c, FILE *fp) */ #include <stdio.h> int main(void) { 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); puts(""); printf("Thank you!\n"); return 0; }
Let’s turn to output of the program as follows
a a v v c c u u 1 1 Thank you!
Notice that program reads in individual characters form stdin writing that to stdout until reads in character ‘1’. ungetc() returns ‘1’ back to the stream. Next call to getchar() and putchar() reads and prints character returned by ungetc().
Note that sending character back to stream isn’t same as writing to it. All streams support at least ungotten of one character. If some stream allows several characters to be back (ungotten) on the stream, they will be read in reverse order that they were pushed.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Apply for Computer Science Internship
- Apply for C Internship
- Practice BCA MCQs
- Practice Computer Science MCQs
- Check Computer Science Books