0

Looking through some old code that is not mine, I ran into this line:

if (ungetc(getc(in), in) != EOF) 

Where in is a file pointer.

I'm unfamiliar with these functions and their use.

Am I interpreting this correctly as if (the end of the file has not yet been reached) ?

Peter
  • 1,334
  • 12
  • 28
  • 2
    Re “I'm unfamiliar with these functions and their use”: Did you look them up, in the C standard or elsewhere? – Eric Postpischil May 26 '23 at 14:20
  • 2
    The first step to understand a function is to look it up in the documentation, for example [here](https://en.cppreference.com/w/c/io/ungetc). Please note that [a certain amount of research is expected before asking a question on Stack Overflow](https://meta.stackoverflow.com/q/261592/12149471). – Andreas Wenzel May 26 '23 at 14:28
  • Yes, I looked them up (hence my interpretation) and yes I was still unsure. – Peter May 26 '23 at 14:40
  • It is [Why is “while( !feof(file) )” always wrong?](https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong) workaround. – 0___________ May 26 '23 at 16:31

1 Answers1

5

It "peeks" at the stream in looking for EOF, without removing the character from the buffer. Or rather it grabs a character then puts it back.

Am I interpreting this correctly as if (the end of the file has not yet been reached) ?

Yes.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 1
    @HolyBlackCat is correct. `feof` won't tell you if there is any data left, it only tells you that *after* you've already tried to read past the end of file. This check guarantees at least one character available to read. – ShadowRanger May 26 '23 at 14:05
  • @HolyBlackCat Yeah you are correct. I removed the part about feof since it just added confusion anyway. – Lundin May 26 '23 at 14:24
  • 4
    It is important to know that `ungetc(EOF, in)` does not push anything back to the stream `in` but returns `EOF`. – Ian Abbott May 26 '23 at 14:37