Skip to content

Instantly share code, notes, and snippets.

@nikp123
Created August 23, 2025 17:25
Show Gist options
  • Select an option

  • Save nikp123/997efcc597069949bd2e5960de3dc27f to your computer and use it in GitHub Desktop.

Select an option

Save nikp123/997efcc597069949bd2e5960de3dc27f to your computer and use it in GitHub Desktop.
C snippet for taking multiple files in as input and guessing the correct output based off of sheer probability.
#include <assert.h>
#include <stddef.h>
#include <stdio.h>
#include <limits.h>
/**
* @return - Element of that list which is the biggest
* @params len - Lenght of that list
* @params n - List of ints that you want to search
**/
size_t biggest(int *n, size_t len) {
int max = 0;
for(int i = 0; i < len; i++) {
if(n[i] > n[max]) {
max = i;
}
}
return max;
}
int main(int argc, char *argv[]) {
int retval = 0;
const size_t filecount = argc - 1;
FILE *fp[filecount];
FILE *output = fopen("output.bin", "wb");
assert(output != NULL);
// batch open
for(int i = 0; i < filecount; i++) {
fp[i] = fopen(argv[1+i], "rb");
assert(fp[i] != NULL);
}
size_t sizes[filecount];
for(int i = 0; i < filecount; i++) {
fseek(fp[i], 0, SEEK_END);
sizes[i] = ftell(fp[i]);
fseek(fp[i], 0, SEEK_SET);
}
size_t average = sizes[0];
for(int i = 1; i < filecount; i++)
assert(average == sizes[i]);
for(int i = 0; i < average; i++) {
char c[filecount];
int n[filecount];
int elements = 1;
for(int j = 0; j < filecount; j++) {
c[j] = 0;
n[j] = 0;
if(j == 0) {
c[j] = fgetc(fp[j]);
n[j] = 1;
continue;
}
char new = fgetc(fp[j]);
for(int k = 0; k <= j; k++) {
if(c[k] == new) {
n[k]++;
} else if (k == j) {
c[k] = new;
n[k] = 1;
elements++;
}
}
}
int max = biggest(n, elements);
if(n[max] >= elements/2) {
fputc(c[max], output);
} else {
fprintf(stderr, "Could not find a sane byte at offset %u. Aborting.\n", ftell(output) + 1);
break;
}
}
fclose(output);
// batch close
for(int i = 0; i < filecount; i++) {
fclose(fp[i]);
}
return retval;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment