MIME Type: Mapping MIME Types to and from File Extensions
This tutorial demonstrates how you can map MIME types to file extensions and vice versa.
Warm-up
Become familiar with the MIME Type API basics by learning about:
-
Getting the MIME Type for a File Extension
Get a MIME type when an extension is known.
-
Getting Extensions for a MIME Type
Get extensions mapped to certain MIME types.
Getting the MIME Type for a File Extension
To get the MIME types of all files in a directory when the extensions are known:
-
To use the functions and data types of the MIME Type API (in mobile and wearable applications), include the <mime_type.h> header file in your application:
#include <mime_type.h>
-
To get a MIME type for a file extension, use the mime_type_get_mime_type() function. The first parameter is the file extension without the leading dot and the second parameter is the MIME type for the given file extension.
The MIME type is 'application/octet-stream' if the given file extension is not associated with any specific file format.
#include <dirent.h> #include <string.h> char *mime_type; int error = mime_type_get_mime_type("jpg", &mime_type);
-
Get the extensions of all files in the resource directory and get their MIME types. To get the directory content, use the dirent structure available in the <dirent.h> header:
struct dirent *pDirent = NULL; DIR *dir; char *res_path = app_get_resource_path(); if (!res_path) // Error handling dir = opendir(res_path); if (dir) { while ((pDirent = readdir(dir)) != NULL) { if (pDirent->d_type != DT_REG) // Only regular files continue;
-
Get the extension from a file name using the strrchr() function available in the <string.h> header. Incrementing the pointer address is necessary, so use the extension without a dot:
char *extension = strrchr(pDirent->d_name, '.'); if (!extension) continue; extension++;
-
Use the mime_type_get_mime_type() function to get the MIME type of each file using the extension pointer as an extension:
mime_type_get_mime_type(extension, &mime_type); // Here you have a mime type in its variable free(mime_type); } closedir(dir); }
Getting Extensions for a MIME Type
To get a list of extensions associated, for example, with an image or jpeg MIME type:
-
To use the functions and data types of the MIME Type API (in mobile and wearable applications), include the <mime_type.h> header file in your application:
#include <mime_type.h>
- Use the mime_type_get_file_extension() function. The parameters are the MIME type, the array of file extensions, and the length of the array of the file extensions (marked as zero if there are none).
char **extension; int length; int error = mime_type_get_file_extension("image/jpeg", &extension, &length); int i; for (i = 0; i < length; i++) // Use extension[i] for (i = 0; i < length; i++) free(extension[i]); free(extension);