Here's my code. I've got print debugging statements in there. The output seems to indicated that everything is going well, but when I open up the files, they are blank. I inspected the JPEGS with xxd
and they all start with the magic number... so I don't know what's going wrong. Does anybody have any ideas for me?
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef uint8_t BYTE;
char fn[7];
int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover infile\n");
return 1;
}
// remember filenames
char *infile = argv[1];
// open input file
FILE *inptr = fopen(infile, "r");
if (inptr == NULL)
{
fprintf(stderr, "Could not open %s.\n", infile);
return 2;
}
int jpegs = 0;
int found_jpeg = 0;
BYTE buffer[512];
do
{
fread(buffer, 512, 1, inptr);
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff &&
(buffer[3] & 0xf0) == 0xe0)
{
if (found_jpeg)
{
printf("Found a NEW jpeg!\n");
sprintf(fn, "%03i.jpg", jpegs);
jpegs ++;
sprintf(fn, "%03i.jpg", jpegs);
printf("Filename %s\n", fn);
FILE *img = fopen(fn, "w");
fwrite(&buffer, sizeof(BYTE), 512, img);
} else
{
printf("Found a jpeg for the first time!\n");
found_jpeg = 1;
sprintf(fn, "%03i.jpg", jpegs);
printf("Filename %s\n", fn);
FILE *img = fopen(fn, "w");
fwrite(&buffer, sizeof(BYTE), 512, img);
}
}
else if (found_jpeg)
{
printf("Writing to existing JPEG...\n");
sprintf(fn, "%03i.jpg", jpegs);
FILE *img = fopen(fn, "w");
fwrite(&buffer, sizeof(BYTE), 512, img);
printf("Succesfully wrote to %s\n", fn);
}
}
while (!feof(inptr));
printf("Total: %d\n", jpegs);
// close infile
fclose(inptr);
// success
return 0;
}