My program to recover JPGs runs and creates the files, but was failing check50. So I ran the debugger, and it looks like it's only recovering a small portion of each JPG. Not sure what I'm doing wrong, and having a hard enough time wrapping my head around this PSET in general, so fixing it has proven to be super frustrating. Help would be appreciated!
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
typedef uint8_t BYTE;
int main(int argc, char *argv[])
{
//check argc to ensure only 1 (technically 2) command line arguments are present
//if more or less, return Usage: ./recover image
if (argc != 2)
{
printf("Error: Must include file name to recover from only.\n");
return 1;
}
//open memory card in read mode
FILE *card = fopen(argv[1], "r");
//if it can't find the file, return error
if (card == NULL)
{
printf("Error: Cannot read file.\n");
return 2;
}
// Open our first file.
int counter = 0;
FILE *output = NULL;
// Create a 512 byte buffer.
BYTE buffer[512];
// while we're not at the end of the card.raw file, read 512 bytes {
while (fread(buffer, sizeof(BYTE), 512, card))
{
// at this point we have 512 bytes of the file.
// check the first 3 to see is a JPG AND.. if we convert hex to binary, then check the high 4 bit and it's 1110 {
if (buffer[0] == 0xff
&& buffer[1] == 0xd8
&& buffer[2] == 0xff
&& (buffer[3] >= 0xe0 && buffer[3] < 0xf0))
{
// YES
// are we working on another jpg?
if (output) {
fclose(output);
}
// YES: close the other file.
// start a new jpg file outout
counter++;
char filename[8];
sprintf(filename, "%03d.jpg", (counter - 1));
output = fopen(filename, "w");
// char filename[8] = ("output%d.jpg", counter); // output0.jpg, output1.jpg...
// FILE *output = fopen(filename, "w");
// copy the 512 to the new jpg output
fwrite(buffer, 512, 1, output);
}
if (output != NULL)
{
// NO
// continue copying
fwrite(buffer, 512, 1, output);
}
}
// also close the very last file.
fclose(output);
// close the card.raw file
fclose(card);
}