0

I am experienceing a problem where nothing is beign read into a buffer array, but for the life of me I am unable to figure out why. I have read through other threads with users experiencing the same proble, but it seems like I am not doing anything wrong. WOuld really appreciate any guidance and help.

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

typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
   FILE *card = fopen(argv[1], "r");
   FILE *img = NULL;
   if (argc != 2)
   {
       printf("Usage: ./recover image\n");
       return 1;
   }
   if (card == NULL)
   {
       printf("Error: unable to open file\n");
       return 1;
   }

   BYTE buffer[512];
   int counter = 0;
   char filename[8];
   while (fread(buffer, sizeof(BYTE), 512, card) != 0)
   {
       if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
       {
           if (counter == 0)
           {
               sprintf(filename, "%03i.jpg", counter);
               img = fopen(filename, "w");
               fwrite(buffer, 1, 512, img);
               counter++;
           }
           else
           {
               fclose(img);
               sprintf(filename, "%03i.jpg", counter);
               img = fopen(filename, "w");
               fwrite(buffer, 1, 512, img);
               counter++;
           }
       }
       else
       {
           fwrite(buffer, 1, 512, img);
       }
   }
   fclose(img);
   fclose(card);
}
1

We know from the problem spec that the JPG files are back to back, but it's not a given that they begin immediately at the start of the .raw file...

Have a look at your loop logic. What happens if the very first fread() doesn't begin with a jpeg header? (It might be full of zero values, for example.) Your code will write it to img, but img is still NULL at this point in time.

1
  • Thank you so much sir, I did not realise that it wasnt a given they began at the start of the .raw file. Thank you for the help! – Bob Tan Dec 6 '20 at 6:12

You must log in to answer this question.

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