0

Here is the code any help is greatly appreciated. Thanks!

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

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{

    bool jpeg = false;
    BYTE buffer[512];
    int imageNumber = 0;
    char number[8];

    if (argc < 2)
    {
        printf("Usage: Usage: ./recover image \n");
        return 1;
    }

    char *card = argv[1];
    //opening "sd card" & making variable to write too.
    FILE *openFile = NULL;
    FILE *data = fopen(card, "r");

    if (data == NULL)
    {
        printf("Card is undreadable. \n");
        return 1;
    }



    while (true)
    {
        if (feof(data))
        {
             break ;
        }

        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            jpeg = true;
        }

        else
        {
            jpeg = false;
        }

        size_t original = fread(buffer, sizeof(BYTE), 512, data);

        if (jpeg == true && openFile != NULL)
        {
            fclose(openFile);
            imageNumber ++;
        }

        if (jpeg == true)
        {
            sprintf(number, "%03i.jpg",imageNumber);
            openFile = fopen(number, "w");
        }

        if (openFile != NULL)
        {
            fwrite(buffer, sizeof(BYTE), original, openFile);
        }    
    }

    fclose(data);
    fclose(openFile);

    return 0;
}
1

The biggest problem here is that the code is trying to test for a signature before actually reading in the data from the input file. It's doing a "Ready, Fire, Aim." Order of actions is important here.

There are other issues, but you should have a chance to work on them first. If you have additional questions on new problems, please open a new question.

Programming hint: Consider how you could incorporate the fread into the while statement. Using while(true) is an invitation to an infinite loop and should be avoided.

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

| improve this answer | |
  • Explained it perfectly and fixed the code! – king2lc Jul 22 at 21:50

You must log in to answer this question.

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