Skip to content

Instantly share code, notes, and snippets.

@geoff-m
Created April 4, 2023 21:52
Show Gist options
  • Save geoff-m/174b298efc5018a37c797136bd51e3b1 to your computer and use it in GitHub Desktop.
Save geoff-m/174b298efc5018a37c797136bd51e3b1 to your computer and use it in GitHub Desktop.
Usage of /usr/bin/file to get the MIME type of a file
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
bool getMimeType(const char* filePath, char* output, int maxOutputLength) {
const char* COMMAND_BASE = "/usr/bin/file -b --mime-type ";
// + 1 for null terminator
char* command = calloc(1, strlen(COMMAND_BASE) + strlen(filePath) + 1);
strcpy(command, COMMAND_BASE);
strcat(command, filePath);
FILE* p = popen(command, "r");
free(command);
if (p == NULL)
return false;
fgets(output, maxOutputLength, p);
return 0 == pclose(p);
}
int main(int argc, char* argv[]) {
if (argc < 2) {
printf("Expected one argument: path to file\n");
return 1;
}
const int MAX_OUTPUT_LENGTH = 256;
char mimeType[MAX_OUTPUT_LENGTH];
if (getMimeType(argv[1], mimeType, MAX_OUTPUT_LENGTH)) {
printf("MIME type: %s\n", mimeType);
return 0;
} else {
printf("Failed to get MIME type.\n");
return 1;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment