Skip to content

Instantly share code, notes, and snippets.

@konsumer
Created September 24, 2023 11:37
Show Gist options
  • Save konsumer/9a226b464e700206b9cca880ecf6ddf0 to your computer and use it in GitHub Desktop.
Save konsumer/9a226b464e700206b9cca880ecf6ddf0 to your computer and use it in GitHub Desktop.
Rudimentary mimetype detection, from first few bytes, in C.
#include "stdio.h"
// Get more from https://en.wikipedia.org/wiki/List_of_file_signatures
const char* detectMime(unsigned char* bytes) {
if (bytes[0] == 0xFF && bytes[1] == 0xD8 && bytes[2] == 0xFF) {
return "image/jpeg";
}
if (bytes[0] == 0x89 && bytes[1] == 0x50 && bytes[2] == 0x4E) {
return "image/png";
}
if (bytes[0] == 0x4F && bytes[1] == 0x67 && bytes[2] == 0x67) {
return "audio/ogg";
}
if (bytes[0] == 0x52 && bytes[1] == 0x49 && bytes[2] == 0x46 && bytes[8] == 0x41) {
return "audio/wav";
}
if ((bytes[0] == 0xFF && (bytes[1] == 0xFB || bytes[1] == 0xF3 || bytes[1] == 0xF2)) || (bytes[0] == 0x49 && bytes[0] == 0x44 && bytes[0] == 0x33)) {
return "audio/mp3";
}
return "application/octet-stream";
}
int main(int argc, char *argv[]) {
if (argc < 2) {
fprintf(stderr, "Usage: %s <file>\n", argv[0]);
return 1;
}
char b[9];
FILE *fptr;
fptr = fopen(argv[1], "r");
fgets(b, 9, fptr);
fclose(fptr);
printf("%s\n", detectMime(b));
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment