0

I have been working on this problem for a while but could never get it to work. Check50 says that the recovered image does not match. When I opened the recovered images manually, they are all blank. I am really really grateful if someone could help me out. Below is my code:

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



int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Error. Try Again.\n");
        return 1;
    }

    char *file = argv[1];

        // open input file
        FILE *inptr = fopen(file, "r");

    // make sure image can be opened
    if(inptr == NULL)
    {
        fprintf(stderr, "Could not open %s\n", file);
        return 2;
    }

    FILE *image = NULL;
    int counter = 0;
    int jpg_count = 0;
    unsigned char buffer[512];

   // Iterate over file contents
    while((fread(buffer, sizeof(unsigned char), 512, inptr)) == 512)
    {
        // Check if the first four bytes are a JPEG signature
        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if(jpg_count != 0)
            {
                fclose(image);
            }


            char filename[8];
            sprintf(filename, "%03i.jpg", counter);
            image = fopen(filename, "w");
            counter++;
        }

        if (jpg_count == 1)
        {
            fwrite(&buffer, sizeof(unsigned char), 1, image);
        }

    }

    // close files
    fclose(inptr);
    fclose(image);

    return 0;

}
0

Took a quick look. The code depends a lot on jpg_count being set from 0 to 1. So, where is jpg_count actually set to 1? I didn't see it anywhere.

As a side note, why create an extra variable called jpg_count? Wouldn't it be easier to use the var counter instead? It is only incremented from 0 when a file is opened.

Maybe you were overthinking things? ;-)

There may be other issues, but this seems to be the immediate problem.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

| improve this answer | |

You must log in to answer this question.

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