2

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().

Evan Teran
  • 87,561
  • 32
  • 179
  • 238
Shashi Bhushan
  • 1,481
  • 3
  • 16
  • 20

3 Answers3

11

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.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
2

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.

0

If you do ungetc on a stream fp, and then you do a getc again, you get back the same character you just put in. If you do putc the "stream moves on", and a subsequent getc will get whatever is after it, if there is anything... The getc and ungetc are used to "peek ahead" and put it back if there is some special case in handling characters e.g.

Henno Brandsma
  • 2,116
  • 11
  • 12
  • Just after putc if i do getc wont i get the same character which i just put in...cause it will be just where file pointer point to...isnt it? – Shashi Bhushan May 21 '11 at 05:34
  • yes, putc moves the file pointer to after that character, which is the output buffer, and indeed (as Jerry said) ungetc puts in back into an input buffer (they could be the same, which what I was assuming) – Henno Brandsma May 21 '11 at 05:41
  • ya so the main difference is ungetc puts in input buffer whereas putc puts it in output buffer... – Shashi Bhushan May 21 '11 at 05:45
  • not only that, but ungetc also ensures that the file pointer stays at that place, while after putc it moves one along. The next putc will be put after this one (if you do nothing inbetween). – Henno Brandsma May 22 '11 at 12:19