0

I´m trying to solve the pset4 recover challenge, but i havent been able to make the program recover the full image, only one part of it. What am i doing wrong ??

This is my code:

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

 typedef uint8_t BYTE;

 int main(int argc, char *argv[])
 {
      if (argc < 2)
      {
          return 1;
      }

// Open memory card
FILE *card = fopen("card.raw", "r");

if (card == NULL)
{
    return 1;
}


// Variables
int file_count = 0;
char filename[9];

BYTE buffer[512];
FILE *img;

// Read 512 bytes until end of card
while (fread(&buffer, sizeof(BYTE), 512, card) == 512)
{
    // If start of new JPEG
    if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
    {
        // If 
        if (file_count == 0)
        {
            // Create new name for img file
            sprintf(filename, "%03i.jpeg", file_count);
            
            // Open img file to write to
            img = fopen(filename, "w");
            
            // Write to img file
            fwrite(&buffer, sizeof(BYTE), 512, img);
        }
        else 
        {
            // Close JPEG file    
            fclose(img);
            
            // Create new name for img file
            file_count++;
            sprintf(filename, "%03i.jpeg", file_count);
            
            // Open img file to write to
            img = fopen(filename, "w");
            
            // Write to img file
            fwrite(&buffer, sizeof(BYTE), 512, img);
        }
    }
    else 
    {
        // Write to currently open filed
        fwrite(&buffer, sizeof(BYTE), 512, img);
    }
}


// Close any remaining files
fclose(card);}
0

The problem with the code is that it doesnt increase the file_count variable, i created an additional variable firstFile, and changed the first if condition to check if its the first file, in that same block, inside the if statement, after all the operations i turn firstFile = 0, that way the loop runs as it should be.

You must log in to answer this question.

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