Get mime type from file extension

I am trying to get the Mime type from an extension, for example .html, to return text/html. I know how to get Mime with an accessible file, but not in a different way. Is there a way to request mime from an extension, at least known?

+4
source share
1 answer

you need to use GContentTypeinside GIO:

https://developer.gnome.org/gio/stable/gio-GContentType.html

and, to be precise g_content_type_guess():

https://developer.gnome.org/gio/stable/gio-GContentType.html#g-content-type-guess

, , ; g_content_type_get_mime_type(), MIME .

g_content_type_guess():

#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <gio/gio.h>

int
main (int argc, char *argv[])
{
  const char *file_name = "test.html";
  gboolean is_certain = FALSE;

  char *content_type = g_content_type_guess (file_name, NULL, 0, &is_certain);

  if (content_type != NULL)
    {
      char *mime_type = g_content_type_get_mime_type (content_type);

      g_print ("Content type for file '%s': %s (certain: %s)\n"
               "MIME type for content type: %s\n",
               file_name,
               content_type,
               is_certain ? "yes" : "no",
               mime_type);

      g_free (mime_type);
    }

  g_free (content_type);

  return EXIT_SUCCESS;
}

, Linux:

Content type for file 'test.html': text/html (certain: no)
MIME type for content type: text/html

: Linux - MIME; , GContentType MIME.

, , , - , .

+5

Source: https://habr.com/ru/post/1525083/


All Articles