Skip to content

Instantly share code, notes, and snippets.

@prateek-parashar
Last active March 26, 2018 12:15
Show Gist options
  • Select an option

  • Save prateek-parashar/cbb3ea4cd4bd44757a7654f68db223ac to your computer and use it in GitHub Desktop.

Select an option

Save prateek-parashar/cbb3ea4cd4bd44757a7654f68db223ac to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
//taking in command line arguements
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr, "Usage : ./recover forensic file\n");
return 1;
}
char *infile = argv[1];
//opening the corrupted file
FILE *corrupt = fopen(infile, "r");
if (corrupt == NULL)
{
fprintf(stderr, "The file cannot be opened\n");
return 1;
}
//using unsigned char as it has a range of 0 to 255
unsigned char *cont = malloc(512);
//variables to control the naming of the recovered jpegs
int i = 0;
char name[8];
if (cont == NULL)
{
fprintf(stderr, "The memory space cannot be allocated\n");
return 2;
}
//reading until the end of file until a beginning of a jpg is encountered
while (fread(cont, 1, 512, corrupt) == 512)
{
//test condition of jpg
if (cont[0] == 0xff && cont[1] == 0xd8 && cont[2] == 0xff && (cont[3] & 0xf0) == 0xe0)
{
do
{
//opening of a new jpg
if (cont[0] == 0xff && cont[1] == 0xd8 && cont[2] == 0xff && (cont[3] & 0xf0) == 0xe0)
{
sprintf(name, "%.3d.jpg", i);
FILE *img = fopen(name, "w");
if (corrupt == NULL)
{
fprintf(stderr, "The jpg file cannot be created\n");
return 3;
}
fwrite(cont, 1, 512, img);
fclose(img);
i++;
}
//appending data blocks at the already opened jpg
else
{
FILE *img = fopen(name, "a");
fwrite(cont, 1, 512, img);
fclose(img);
}
}
while (fread(cont, 1, 512, corrupt) == 512);
}
}
free(cont);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment