Created
April 4, 2023 21:52
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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