0
#include <stdio.h>
#include <stdint.h>

typedef uint8_t  BYTE;

int main(int argc, char* argv[])
{ 
    // checks proper user input on command line
    if (argc != 2)
    {
        fprintf(stderr, "Usage: ./recover image\n");
        return 1;
    }
    // opens .raw file and checks for errors
    FILE *inptr = fopen(argv[1], "r");
    if (inptr == NULL)
    {
        fprintf(stderr, "Could not open file\n");
        return 2;
    }

    // creates buffer to store 512 bytes
    BYTE buffer[512];
    // keeps track of jpegs found
    int jpegCount = 0;
    // initializes filename and file variables for writing
    char filename[8];
    FILE *currentjpeg;
    // repeats until EOF
    while (fread(buffer, 1, sizeof(buffer), inptr) == 512)
    {
         // do stuff
    }
    fclose(inptr);
}

The debugger says fread returns 0 on the while condition (I checked by making a few variables) and I don't understand why.

3
  • Interesting. I ran the code and it works as expected. The fread returns 512, not 0. Is it possible that you changed the source code and forgot to resave it, or didn't recompile? Easy check: put a printf inside the loop. If the return value isn't 512, the loop won't run.
    – Cliff B
    Commented Jan 23, 2018 at 2:46
  • @CliffB well I tried several ways of checking the return value of fread and it always returns 0, and it never enters the loop. Commented Jan 23, 2018 at 3:11
  • when you execute the program, are you giving it a valid filename as a parameter and that file exists in the same directory? I'm assuming that you DID resave the code after making changes and then recompiled. Try running it at the command line and not in the debugger to make sure it's getting a valid input file.
    – Cliff B
    Commented Jan 23, 2018 at 3:21

1 Answer 1

1

I tested with your code and it's definitely correct, as @cliff has said in the commment. Do make sure the file you are opening actually has more than 512 bytes. Perhaps your rawfile has been corrupted? fread is returning 512

1
  • Yes it was corrupted, I probably did something to it previously, thanks. Commented Jan 23, 2018 at 3:49

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .