Safety of reading past end of file

I've googled around and didn't find the answer I'm looking for.

appparently, eof() and feof() return EOF only if you have already attempted to read past the end of a file, so then it must be safe to read past a file by at least one byte. In some 'oops' test cases, I've read quite far beyond the end of a file and it crashes after a whole lots of read attempts. So my question is,

how far can you _safely_ attempt to read past the end of a file?
Safely i.e. doesn't crash your application?
All those files are also in the memory, much like all your data in the program. So, your question is equivalent to: "how far can you "safely" attempt to read past the end of an array?"
eof() and feof() return EOF only if you have already attempted to read past the end of a file, so then it must be safe to read past a file by at least one byte.

That's an incorrect conclusion. eof() and feof() report that the recent attempt to read from the file using C++ and C I/O, respecfively, failed because there was nothing more to read. No bytes were actually read from anywhere.

I've read quite far beyond the end of a file

That's not possible using standard I/O routines. Show the code.
Last edited on
when I said I've read quite far, I mean only I had a runaway loop that kept _attempting_ to read beyond the end of a file thousands of times. ( the crash was actually attempting to read into a char buffer, not the read itself, I found out).

So I've created this test program and let it run for quite some time, and it just chugs along attempting to read but never crashes, so Chubbi is correct.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <stdio.h>
#include <iostream>

int main ( void ) {
        FILE *file=fopen( "foo", "r" );
        char buf;

        if ( file == NULL ) {
                std::cout << "file not opened\n";
                return -1;
        }

        std::cout << "reading\n";
        fflush( stdout );

        // infinite loop intended, to show that it is 'safe' to attempt to read beyond a file
        // the read will not happen if it is past the end of the file
        for ( int i=0; ; i++ )
                fread( &buf, 1, 1, file );

        return 0;
}
Brandon, I'm sorry, but youre code is soo LOL!!! You use iostream and stdio in the same code!! Please, PLEASE, use fstream with iostream! Only if you are one of those people who like stdio better than iostream, then use only stdio! Your combination makes me laugh!!
Your message makes me LOL!!!

C++ is 100% bckward compatible with C, and these functions don't even mingle with one another. There is nothing wrong with my code aside from your own personal taste. The code is completely valid.

Please educate yourself before you start throwing advice around. Maybe start here: http://stackoverflow.com/questions/5570361/file-vs-fstream
Last edited on
Topic archived. No new replies allowed.