Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/70.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C 从文件扩展名获取Mime类型_C_Gtk_Gnome - Fatal编程技术网

C 从文件扩展名获取Mime类型

C 从文件扩展名获取Mime类型,c,gtk,gnome,C,Gtk,Gnome,我试图从扩展名中获取Mime类型,比如。html应该返回text/html。 我知道如何获得Mime文件可用,但不是其他方式。是否有一种方法可以从扩展名(至少是已知的扩展名)查询mime?您需要在GIO内部使用GContentType: 准确地说,g\u content\u type\u guess(): 它接受文件名或文件内容,并返回猜测的内容类型;从那里,您可以使用g\u content\u type\u get\u mime\u type()获取内容类型的mime类型 这是一个如何使用

我试图从扩展名中获取Mime类型,比如
。html
应该返回
text/html

我知道如何获得Mime文件可用,但不是其他方式。是否有一种方法可以从扩展名(至少是已知的扩展名)查询mime?

您需要在GIO内部使用
GContentType

准确地说,
g\u content\u type\u guess()

它接受文件名或文件内容,并返回猜测的内容类型;从那里,您可以使用
g\u content\u type\u get\u mime\u type()
获取内容类型的mime类型

这是一个如何使用
g\u content\u type\u guess()
的示例:

说明:在Linux上,内容类型是MIME类型;这在其他平台上是不正确的,这就是为什么必须将
GContentType
字符串转换为MIME类型


此外,如您所见,仅使用扩展名将设置布尔值为“确定”标志,因为扩展名本身不足以确定准确的内容类型。

这将要求文件正确显示吗?我知道我问的问题并不常见,但我想知道已知文件类型的mime类型。我可以解析/etc/mime.types,但我更愿意使用这样做的库。感谢您提供了一个很好的示例。不,它不需要文件存在:您只需要它的名称。另外,/etc/mime.types在任何现代Linux上都是毫无意义的:你想要共享mime信息数据库,它是freedesktop.org的一部分:这样我就可以输入任何虚拟名称,比如dummy.html?这就是我需要的。我现在就接受它!感谢伊巴西的友好而清晰的回答。在测试这段代码的过程中,我遇到了一些类似的错误,因此我决定共享用于编译它的命令:gcc
pkg config--cflags--libs dbus-glib-1 dbus-1 glib-2.0 gthread-2.0 gio-2.0
test.c
#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;
}
Content type for file 'test.html': text/html (certain: no)
MIME type for content type: text/html