Skip to content

Instantly share code, notes, and snippets.

@nezvers
Created December 1, 2025 09:05
Show Gist options
  • Select an option

  • Save nezvers/7f14213844e6824e2cf434b1a41703e1 to your computer and use it in GitHub Desktop.

Select an option

Save nezvers/7f14213844e6824e2cf434b1a41703e1 to your computer and use it in GitHub Desktop.
Binary extraction in C
#include <stdio.h>
void carve_file(const char *input_file, const char *output_file, size_t start_byte, size_t end_byte){
FILE *file_in = NULL;
FILE *file_out = NULL;
file_in = fopen(input_file, "rb");
if (!file_in) {
printf("Failed to open input file - %s\n", input_file);
goto defer;
}
file_out = fopen(output_file, "wb");
if (!file_out) {
printf("Failed to open output file - %s\n", output_file);
goto defer;
}
if (fseek (file_in, start_byte, SEEK_SET)){
printf("Failed to set seek position - %s: %zu\n", input_file, start_byte);
goto defer;
}
char buffer;
while (fread(&buffer, sizeof(buffer), 1, file_in) != 0){
if (fwrite(&buffer, sizeof(buffer), 1, file_out) == 0){
printf("Failed to write a byte - %s: from %s %zu\n", output_file, input_file, ftell(file_in));
goto defer;
}
if (ftell(file_in) >=end_byte){
goto defer;
}
}
defer:
if (file_in) fclose(file_in);
if (file_out) fclose(file_out);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment