Skip to content

Instantly share code, notes, and snippets.

@edieblu
Created March 16, 2021 16:10
Show Gist options
  • Save edieblu/6bb86e19f96d1a3e39582b7c2a6d831e to your computer and use it in GitHub Desktop.
Save edieblu/6bb86e19f96d1a3e39582b7c2a6d831e to your computer and use it in GitHub Desktop.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
// generate new jpg files from recovered data
// accept exactly one command-line argument (img filename)
// if not one arg, print error message and return 1
// if cannot open file also return 1
// files should be named ###.jpg starting with 000.jpg
// use malloc and free
// jpg file header signature: Oxff Oxd8 Oxff Oxe{0-f}
// jpg file tail signature: Oxe{0-f}
// write 512 bytes until new jpeg is found (they are stored back to back)
typedef uint8_t BYTE;
int BLOCK_SIZE = 512;
int is_jpeg_header(BYTE block[])
{
// jpg file header signature: Oxff Oxd8 Oxff Oxe{0-f}
return (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] & 0xf0) == 0xe0);
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
printf("Please provide one file name\n");
return 1;
}
FILE *source_file = fopen(argv[1], "rb");
if (source_file == NULL)
{
printf("Can't open the file\n");
return 1;
}
FILE *output_file;
// int *block = malloc(BLOCK_SIZE);
BYTE block[BLOCK_SIZE];
// read file
// data: buffer
// size: in bytes
// number: of el to read
// intptr: FILE * to read from
// fread(data, size, number, inptr)
int bytes_read = fread(block, sizeof(BYTE), BLOCK_SIZE, source_file);
int counter = 0;
int currently_writting = 0;
char image_file_name[] = "000.jpg";
while (bytes_read == BLOCK_SIZE)
{
if (is_jpeg_header(block))
{
if (currently_writting)
{
fclose(output_file);
}
// saving to a file
// print a 3-digit integer
// this would result in 002.jpg
sprintf(image_file_name, "%03i.jpg", counter);
counter++;
output_file = fopen(image_file_name, "wb");
currently_writting = 1;
}
if (currently_writting)
{
fwrite(block, sizeof(BYTE), BLOCK_SIZE, output_file);
}
bytes_read = fread(block, sizeof(BYTE), BLOCK_SIZE, source_file);
}
// close file
fclose(source_file);
if (currently_writting)
{
fclose(output_file);
}
// free(block);
return 0;
}
// pracicing bitwise magic 🪄
// f7 1111 0111
// f0 1111 0000
// & 1111 0000
// e7 1110 0111
// f0 1111 0000
// & 1110 0000 ✅
// 57 0101 0111
// f0 1111 0000
// & 0101 0000 🔴
// e0 1110 0000
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment