1

I'm pretty new to programming, and recently, my class started file handling using C++. My question is what triggers an end of file? Just like there is "\n" for a new line character, is there something specific that the compiler looks at to know if it is eof? An answer with lots of juicy details is much appreciated!

Nicol Bolas
  • 378,677
  • 53
  • 635
  • 829
  • 1
    "What triggers and End of File?" - that there is no more data in the file. That you are exceeding the number of bytes in the file. What else would it be? – Jesper Juhl Jul 27 '19 at 11:21
  • 1
    The `eof` condition flag on iostreams is triggered by attempting to read past the end of the file – M.M Jul 27 '19 at 11:23
  • 2
    End of file is triggered when reading past the last character that is present in an input stream. Different systems recognise that occurrence in different ways but, however it is recognised, the standard library functions convert that into an appropriate states (e.g. set a flag in the stream state). – Peter Jul 27 '19 at 11:36
  • 3
    This may help you avoid a bug in the future: https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-i-e-while-stream-eof-cons – drescherjm Jul 27 '19 at 11:47
  • 2
    https://latedev.wordpress.com/2012/12/04/all-about-eof/ has a good overview of EOF. – Shawn Jul 27 '19 at 12:41

1 Answers1

3

End Of File (EOF) isn't tied to a specific character like End Of Line (EOL / LF) is. It's simply a state to signal "we're at the end of this file", different methods will have different way of signalling this. Usually this EOF "state" is triggered when the code tries to read past the end of the file.

For example, when using an ifstream, the get() method will return Traits::eof() if we've read all the data in the file. After that point, calling std::ifstream::eof() will return true. This only applies to C++'s streams though, different methods and/or languages may have different ways of signalling EOF, it's not a universal thing like EOL is, there's no character to describe EOF.

Hatted Rooster
  • 33,170
  • 5
  • 52
  • 104
  • 1
    Very, very strong emphasis on the "tries to read past the end of file" part, rather than _just_ at the end. I wasted a lot of time and stupid band-aid code when I first started with C++ on not knowing that distinction. – hegel5000 Jul 27 '19 at 14:35
  • @SombreroChicken This is exactly what I was trying to find! Before reading this, I was guessing that there must be some specific character that would signal an eof. What I take from all the responses above is that an eof is simply defined as a point after which no further bytes can be read (because the file has ended, obviously). Various methods are there to find this out. Cool. It feels good now that I understand this! – Apekshik Panigrahi Jul 27 '19 at 15:19