Can somebody please help with this question?

... and also I tried to debug and apparently it doesn't run my while loop and i don't understand why.

while (fread(buffer, 512, 1, fraw) == 1)

so while(true) will loop if it is true. fread(buffer,512,1,fraw) will return 1 if it reads successfully. Thus it is true and will loop. Is my logic correct? Please help! Thank you.

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

typedef uint8_t BYTE; // Declaring Byte as an unsigned integer 8 BIT !

int main(int argc, char *argv[])
    if(argc != 2){
        printf("Usage: ./recover image\n");
        return 1;

    char* inFile = argv[1];

    // Open memory card File
    FILE* fraw = fopen (inFile, "r");

    if (fraw == NULL)
        fprintf(stderr, "Could not open %s.\n", inFile);
        return 2;

    BYTE buffer[512]; // Creating a buffer of size 512 for a block
    FILE *JPG;
    int counter=1;
    char filename[20];

    while (fread(buffer, 512, 1, fraw) == 1) // fread returns 1 if successful
        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)  // Start of JPEG
            if(counter>1) // If File is open, close the pointer
            sprintf(filename, "%03i.jpg", counter); // Create file name
            JPG = fopen(filename, "w"); // Create new file pointer
            fwrite(&buffer, sizeof(buffer), 1, JPG); // Write buffer to the image
            if(JPG) // Found JPEG
                fwrite(&buffer, sizeof(buffer), 1, JPG); // Write buffer to the image

Your logic is correct. Your code works fine, recovering 50 files.

  • What do you mean by recovering 50 files? Why is his while loop not running? – Christopher Holder Nov 5 '19 at 10:54
  • I mean, that I pasted your code in file in online IDE (on my account), saved it, compiled it, run it and it created 50 .jpg files out of my image file. I opened them and they were all good. Your problem not in your code. Re-download your image file, check its location maybe. If you'll add a number of printf("loop Nx: read %d bytes", fread(...) ) it'll be easier to debug. – Rustam A. Nov 5 '19 at 19:33
  • Very helpful thanks for sharing your code it helped me find my fault - just that I had the new file name string defined as a char* and gave it value "000" instead of char array – ShippingTycoon Mar 2 '20 at 23:08

You must log in to answer this question.

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