I'm having problem with my pset 4 recover assignment,
my code can compile and produce 49 jpg documents with the right name, but check50 told me they don't match with the right jpgs.
Is there anything wrong with my logic? Thanks in advance!
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
int BLOCK_SIZE = 512;
int main(int argc, char *argv[])
{
// Ensure proper usage
if (argc != 2)
{
printf("Usage: ./recover IMAGE\n");
return 1;
}
// Open input file
FILE *infile = fopen(argv[1], "r");
if (infile == NULL)
{
printf("Could not open %s.\n", argv[1]);
return 2;
}
//allocate memory for file name and for buffer
char *filename = malloc(8 * sizeof(char));
BYTE *buffer = malloc(BLOCK_SIZE * sizeof(BYTE));
int k = 0;
FILE *outfile;
while (fread(buffer, sizeof(BYTE), BLOCK_SIZE, infile) == BLOCK_SIZE)
{
//find the signature
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
{
//close the outfile already opened(if there is one)
if (k > 0)
{
fclose(outfile);
}
//create new file and start writing
k = k + 1;
sprintf(filename, "%03i.jpg", k-1);
outfile = fopen(filename,"w");
if (outfile == NULL)
{
printf("Could not open %s.\n", filename);
}
fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
}
//if this block has no signature, directly write
else
{
if (k > 0)
{
fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
}
}
}
//finishe writing the last picture
if (k > 0)
{
fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
}
// Close outfile
fclose(outfile);
fclose(infile);
free(filename);
free(buffer);
return 0;
}