Skip to content

Instantly share code, notes, and snippets.

@i5ar
Forked from jcoryalvernaz/recover
Last active January 28, 2019 04:43
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 i5ar/10cc398fccec830cb13432c46dd75727 to your computer and use it in GitHub Desktop.
Save i5ar/10cc398fccec830cb13432c46dd75727 to your computer and use it in GitHub Desktop.
Recover card
#include <stdio.h>
#include <stdbool.h>
int main(int argc, char *argv[])
{
// Make sure that I have one command line argument
if (argc != 2)
{
fprintf(stderr, "Usage: ./recover image\n");
return 1;
}
// Open the file entered into the command line
FILE *file = fopen(argv[1], "r");
// If the file does not exist, throw an error
if (file == NULL)
{
fprintf(stderr, "Could not open %s\n", argv[1]);
return 1;
}
// Create outfile for picture
FILE *img = NULL;
// Create buffer and filename arrays
unsigned char buffer[512];
char filename[8];
// Set counter for filename
int counter = 1;
// Set flag
bool flag = false;
// Read the file
while (fread(buffer, 512, 1, file) == 1)
{
// Check if we are at the beginning of a JPEG
if (buffer[0] == 0xff &&
buffer[1] == 0xd8 &&
buffer[2] == 0xff && (
buffer[3] & 0xf0) == 0xe0)
{
// Close current JPEG, so we can start reading the next
if (flag == true)
{
fclose(img);
}
// Condition for found JPEG
else
{
flag = true;
}
sprintf(filename, "%03i.jpg", counter++);
img = fopen(filename, "w");
}
if (flag == true)
{
fwrite(&buffer, 512, 1, img);
}
}
// Close all files
fclose(img);
fclose(file);
// Success
return 0;
}
import sys
import itertools
def main():
try:
raw = sys.argv[1]
except IndexError:
print('Usage: python recover.py card.raw')
sys.exit(1)
try:
with open(raw, "rb") as file:
flag = False
size = 512
inner = []
outside = []
for i in itertools.count():
buffer = file.read(size)
if len(buffer) == 512:
if buffer[0] == 0xff and \
buffer[1] == 0xd8 and \
buffer[2] == 0xff and \
buffer[3] & 0xf0 == 0xe0:
if flag == True:
outside.append(b''.join(inner))
else:
flag = True
inner = [buffer]
else:
if flag:
inner.append(buffer)
else:
outside.append(b''.join(inner))
for counter, i in enumerate(outside):
filename = '{:03d}.jpg'.format(counter+1)
with open(filename, "wb") as img:
img.write(i)
break
except IOError:
print('Could not open {}'.format(raw))
sys.exit(1)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment