Detecting EOF when reading and writing

So I am doing an assignment for an online course, which involves recovering deleting jpgs from a camera memory card. I have written the program and it recovers all 50 jpgs, but I can't properly detect the EOF (end of the copy of the memory card file called card.raw). On each iteration through an endless loop I read a block of 512 bytes and then decide what to do with it based on whether it's the start of a jpg or not and whether a jpg has already been found.

What I want to do is use fread() in an if statement to check whether I have reached the end of the input file. Whilst reading each byte I want to check if there is another to read (and hence Im not at the EOF), here is the relevant code snippet. The enitire program runs, and recovers the jpgs but I get a long error message, and it's something to do with how I check for the EOF.

Any advice appreciated :)

1
2
3
4
5
6
7
8
9
10
  for(int x = 0; x < 512; x++)
        {
            BYTE byte;
            if(fread(&byte, sizeof(BYTE), 1, inptr) == 0)
            {
                fclose(outptr); // close the file I'm writing to
                break; // break out of the endless for(;;) loop where fclose(inptr) s executed
            }
            byte_array[x] = byte;
         }
If fread fails it returns -1 and sets errno. One of the errno values means and of file I think. Look it up.
Your comments don't match the source code. The break statement exits the loop you have shown in the snippet, not some other endless for(;;) loop. Perhaps you need to show more code?

jlb - winner! Thanks so much, that was exactly problem, I thought break was getting me out of my larger for(;;) loop but it was only getting me out of the for loop I showed. I want it to end the program when fread fails to read a byte, so I changed it to the following and now it works perfectly :)

1
2
3
4
5
6
7
8
9
10
11
12
for(int x = 0; x < 512; x++)
        {
            BYTE byte;
            if(fread(&byte, sizeof(BYTE), 1, inptr) == 0)
            {
                fclose(outptr); // close the file I'm writing to
                fclose(inptr);
                return 0;
                //break; // break out of the endless for(;;) loop where fclose(inptr) s executed
            }
            byte_array[x] = byte;
        }
Hi,

You could put that bit of code in it's own function, so when you return from it - you don't end the entire program.

Since this is a C++ forum, I'm going to give you a C++ answer:

http://en.cppreference.com/w/cpp/io/basic_ifstream
Topic archived. No new replies allowed.