I've spent hours and hours on this code but I can't get any picture out of raw file. I tracked the problem with gdb and figured that when the it reaches to place to test for signature of jpeg it does not match with the condition. So I printed the temp[0] value many times in almost 5 iterations but non was ff. I don't get where the problem is, but something should be wrong with the placeholder of the infile. Can anyone help me please? It's getting really frustrating.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
// prototypes
int fsize(FILE *fp);
int main(int argc, char* argv[])
{
if (argc != 1)
{
printf("Usage: recover currupted-file");
return 1;
}
// opening the corrupted file
FILE* infile = fopen("card.raw", "r");
if (infile == NULL)
{
return 1;
}
// declaring and initializing output filename
int filenumber = 0;
char* filename = malloc(8 * sizeof(char));
FILE* outfile = NULL;
// allocating memory to temp read variable
uint8_t temp[512];
//declaring a variable for file size
long filesize = fsize(infile);
for (int i = 0; i < filesize; i += 512)
{
// reading every 512 Bytes to a temp
fread(&temp, sizeof(temp), 1, infile);
if (temp[0] == 0xff && temp[1] == 0xd8 && temp[2] == 0xff && (temp[3] == 0xe0 || temp[3] == 0xe1))
{
if (filenumber > 0)
{
fclose(outfile);
}
sprintf(filename, "%3i.jpg", filenumber);
FILE* outfile = fopen(filename, "w");
if (outfile == NULL)
{
return 1;
}
filenumber++;
fwrite(temp, 512, 1, outfile);
}
else if (filenumber > 0)
{
fwrite(temp, 512, 1, outfile);
}
}
free(filename);
fclose(outfile);
fclose(infile);
}
// file size finder code
int fsize(FILE *fp)
{
//find current place holder to return to later
int last=ftell(fp);
fseek(fp, 0, SEEK_END);
int size=ftell(fp);
//go back to where we were
fseek(fp,last,SEEK_SET);
return size;
}