I having trouble generating clear images. I am able to generate the 50 JPEGs but they are just random colors or pixelated. I am however, not receiving an "Invalid or unsupported" file format error. I have looked through past questions regarding this topic and I believe that I am using the fwrite function correctly. Any hints would be appreciated.

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

typedef uint8_t BYTE; //typedef allows you to rename a data type (i.e int can be renamed as INT and still have the same meaning); 'uint8_t' means 'byte'

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

//unsigned char *B[512]; //might need to create as a 'struct'
char *infile = argv[1];
FILE *inptr = fopen(infile, "r"); //Must always account if file cannot be opened

    if (inptr == NULL)
        fprintf(stderr, "Could not open\n");// %s.\n", inptr);
        return 2;
//iterate accross JPEG
char filename[8];
  int counter = 0;
  int k = 0; //counter for number of JPEG files

  FILE *img;
 BYTE *buffer = NULL;
 //int count = 0; //test
    while (fread(BLOCK, 1, sizeof(BLOCK), inptr) == 512) // or == 1 //for true statement)

    if(BLOCK[0] == 0xff && BLOCK[1] == 0xd8 && BLOCK[2] == 0xff && (BLOCK[3] & 0xf0) == 0xe0 && counter > 0) //checks for all other JPEG
        sprintf(filename, "%03i.jpg", k);
        img = fopen(filename, "w");

    if(BLOCK[0] == 0xff && BLOCK[1] == 0xd8 && BLOCK[2] == 0xff && (BLOCK[3] & 0xf0) == 0xe0 && counter == 0) //checks for first JPEG

    sprintf(filename, "%03i.jpg", k); //allows you to dynamically allocate string to a variable
    img = fopen(filename, "w"); //create file and filename
    if (counter == 0)

    //buffer = malloc(512);
    //*buffer = *BLOCK;
    fwrite(BLOCK, 1, 512, img);




I made two simple mistakes that may help others out:

One simple mistake is that I set the counter for jpeg files at "1". Check50 wants you to start from "000.jpg" to "049.jpg" and NOT "001.jpg" to "050.jpg". If you do the latter then even though the images will be correct Check50 will not read it as being correct since the images are not labeled starting from "000.jpg".

Make sure to set your zoom function to a good magnification. Initially, the only reason why my images were blurry was because the zoom function was set to 500%.

  • Glad you figured it out. Here's a new challenge for you. Can you make the program more efficient? You should be able to eliminate one of the if(BLOCK... code blocks and the if/continue block. Happy coding! ;-)
    – Cliff B
    Mar 11 '20 at 20:04
  • Thanks for the challenge, it helped me understand the code better!
    – Gil Ong
    Mar 20 '20 at 20:11

You must log in to answer this question.

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