c - 从文件扩展名获取 Mime 类型

标签 c gtk gnome

我正在尝试从 .html 等扩展名中获取 Mime 类型,应该返回 text/html。 我知道如何让 Mime 文件可用但不是其他方式。有没有办法从扩展中查询 mime,至少是已知的?

最佳答案

你需要在 GIO 中使用 GContentType:

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

准确地说是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 类型。

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

关于c - 从文件扩展名获取 Mime 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21532227/

相关文章:

javascript - 如何使用 Gjs Gnome Javascript 包含文件

c - 如何在执行过程中向文本文件添加信息? C

c - 如何从缓冲区中逐字读取仅由 ":"分隔的内容?

c - C标准库中有类似 `fcntl()`的函数吗?

python - 'gi.repository.Gtk' 对象没有属性 'gdk'

linux - 安装新主题时遇到问题 (Ubuntu 14.04)

c - 检查字符串是否为 "Balanced"的递归函数

c - 使用 C 函数 notify_notification_update() 的段错误

macos - FSharp.Charting.Gtk 在启动时崩溃

ubuntu - 代理问题 Gnome 3 和 Chrome 12