Last active
September 28, 2023 10:04
-
-
Save mhofwell/de4eee804ae082798c75ba83340255db to your computer and use it in GitHub Desktop.
JPEG Recovery from Memory in C
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Recovers JPEGs from a .raw file by searching for JPEG headers and writing all of the bytes | |
// between headers to different out files. | |
#include <stdio.h> | |
#include <string.h> | |
#include <math.h> | |
#include <stdlib.h> | |
#include <ctype.h> | |
#include <stdint.h> | |
int main(int argc, char *argv[]) | |
{ | |
// check for valid argv | |
if (argc != 2) | |
{ | |
printf("Usage: ./recover image"); | |
return 1; | |
} | |
// access the FILE via the *readFile pointer. | |
FILE *readFile = fopen(argv[1], "r"); | |
// error handle empty file | |
if (readFile == NULL) | |
{ | |
printf("Empty file!"); | |
return 2; | |
} | |
// reserve 512 bytes in heap as unsigned chars | |
unsigned char *buffer = malloc(512); | |
// create a simple array of 8 bytes to hold the filename chars | |
char filename[8]; | |
// initialize the JPEG count. | |
int count = 0; | |
// initialize a new FILE type to write to. | |
FILE *writeFile = NULL; | |
// while we're able to read in 512 byte blocks | |
while (fread(buffer, sizeof(buffer), 1, readFile) == 1) | |
{ | |
// if its the start of a new JPEG denoted by the signature of the first 5 bytes of data in the next block of the buffer array. | |
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0) | |
{ | |
// if the JPEG contains something && a new header was detected, close the writefile. | |
if (writeFile != NULL) | |
{ | |
fclose(writeFile); | |
} | |
// create a new filename | |
sprintf(filename, "%03i.jpg", count); | |
// open the writeFile | |
writeFile = fopen(filename, "w"); | |
// write the current 512 byte block to the current writeFile | |
fwrite(buffer, sizeof(buffer), 1, writeFile); | |
// add to the count | |
count++; | |
} | |
else | |
{ | |
if (writeFile != NULL) | |
{ | |
// if no new header, write the next 512 byte block to the current writeFile | |
fwrite(buffer, sizeof(buffer), 1, writeFile); | |
} | |
} | |
} | |
// free heap memory | |
free(buffer); | |
// close your writeFile | |
fclose(writeFile); | |
// close your readFile | |
fclose(readFile); | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Check 7:
Solution:
Line 44:
and at the end :