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

int main (int argc, char *argv[1])
{
  // ensure the arguments are correct
  if (argc != 2)
    {
      fprintf(stderr, "Usage: ./recover filename\n");
      return 1;
    }

  char *filename = argv[1];

  // creates the pointer to the file
  FILE *inptr = fopen(filename, "r");
  if (inptr == NULL)
    {
      fprintf(stderr, "Could not open the file %s.\n", filename);
      return 2;
    }

  u_int8_t * block = malloc(512*sizeof(u_int8_t));
  int a = 0;
  char *output;
  int i = 0;
  FILE *img;
  // read bytes until reaches the 0 part in the end of a file.
  while (fread (&block[a], sizeof(u_int8_t), 1, inptr) != 0)
    {
      if (a == 3)
        {
          // checkpoint at a = 3, check if we have a new file
          if (block[0] == 0xff &&
              block[1] == 0xd8 &&
              block[2] == 0xff &&
              (block[3] & 0xf0) == 0xe0)
            {
              if (i > 0)
                {
                  fclose(img);
                }
              output = malloc(8*sizeof(char));
              sprintf(output, "%03i.jpg", i);
              i++;
              img = fopen(output, "w");
              for (int j = 0; j < 4; j++)
                {
                  printf ("%d", j);
                  fwrite(&block[j], sizeof(u_int8_t), 1, img);
                }
              printf("%s\n", output);
            }
          else if (i > 0)
            // writes if it's not a header, but it is still parsing an img file
            {
              fwrite(&block[3], sizeof(u_int8_t), 1, img);
            }
        }
      // just write things down if it's inside a jpeg block
      else if (i > 0)
        {
          fwrite(&block[a], sizeof(u_int8_t), 1, img);
        }
      a++;
      // check if we are still on the same block and deal with block 'turning'
      if (a == 512)
        {
          a = 0;
        }
    }
  fclose(img);
  free(block);
  free(output);
  return 0;
}

I get all images in my computer and in cs50 IDE, but I'm unable to pass check50. I had checked another question with the same problem and it doesn't seem that I'm checking headers in the middle of blocks.

The code I run in cs50 IDE is slightly different on types, but I'm sending this version because it has more comments.

1

I figured it out, my program was writing extra bytes of the next file header into the end of the previous file. The photos seemed fine, but they had an extra header garbage at the end.

  • I too had the same problem. I found it out by opening the images in the hex format in the CS50 IDE and checking the last set of 512 bytes. – Vikas Nov 17 '19 at 14:52

You must log in to answer this question.