Skip to content

Instantly share code, notes, and snippets.

@bruce-mcgoveran
Created July 1, 2017 15:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bruce-mcgoveran/d487f57a2f6033e735a5f9fef57669bc to your computer and use it in GitHub Desktop.
Save bruce-mcgoveran/d487f57a2f6033e735a5f9fef57669bc to your computer and use it in GitHub Desktop.
/**
* recover.c
* 30 Jun 17
*
* Recovers JPEGs from a source file.
*
*/
#include <stdint.h>
#include <stdio.h>
#define BLOCK 512
#define TRUE 1
#define FALSE 0
typedef uint8_t BYTE;
int main(int argc, char* argv[])
{
// check program usage
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
FILE* in;
FILE* out;
BYTE buffer[BLOCK];
int index;
int in_file;
char filename[9];
// open source file
in = fopen(argv[1], "r");
if (in == NULL)
{
fprintf(stderr, "Unable to open source file\n");
return 2;
}
index = 0;
in_file = FALSE;
// check source file block by block for JPEGs
while (fread(&buffer, sizeof(BLOCK), 1, in))
{
// check for start of next JPEG
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
if (in_file)
{
// close current file
fclose(out);
}
// open new image file and write buffer to it
sprintf(filename, "%03i.jpg", index++);
filename[8] = '\0';
out = fopen(filename, "w");
if (out == NULL)
{
fprintf(stderr, "Unable to open destination image file\n");
return 3;
}
fwrite(&buffer, sizeof(BLOCK), 1, out);
in_file = TRUE;
}
else // continue writing to current image file
{
if (in_file)
{
fwrite(&buffer, sizeof(BLOCK), 1, out);
}
}
}
// need to flush any bytes remaining in buffer; they belong to the last JPEG
for (int i = 0; i < BLOCK; i++)
{
if ((char)buffer[i] == EOF)
{
fwrite(&buffer[i], sizeof(BYTE), 1, out);
// printf("%i\n", i);
fclose(out);
break;
}
else
{
fwrite(&buffer[i], sizeof(BYTE), 1, out);
}
}
// success
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment