Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between putc and ungetc?

Tags:

c++

c

function

int ungetc(int c, FILE *fp) pushes the character c back into fp, and returns either c, or EOF for an error.

where as int putc(int c, FILE *fp) writes the character c into the file fp and returns the character written, or EOF for an error.

//These are the statements from K&R. I find myself confused, because putc() can be used after getc and can work as ungetc. So whats the use in specifically defining ungetc().

like image 394
Shashi Bhushan Avatar asked Feb 03 '26 12:02

Shashi Bhushan


2 Answers

putc writes something to output, so it appears on the screen or in the file to which you've redirected output.

ungetc put something back into the input buffer, so the next time you call getc (or fgetc, etc.) that's what you'll get.

You normally use putc to write output. You normally use ungetc when you're reading input, and the only way you know you've reached the end of something is when you read a character that can't be part of the current "something". E.g., you're reading and converting an integer, you continue until you read something other than a digit -- then you ungetc that non-digit character to be processed as the next something coming from the stream.

like image 160
Jerry Coffin Avatar answered Feb 06 '26 00:02

Jerry Coffin


ungetc works with streams opened for read and doesn't modify the original file. putc works on streams opened for write and actually writes the byte to the file.

like image 42
Geoffrey Elliott Avatar answered Feb 06 '26 00:02

Geoffrey Elliott