windows客户端开发--获取windows系统中文件的MIME

文章介绍了MIME的含义,指出依赖文件后缀名判断类型的问题,并提出使用Windows API `FindMimeFromData`来准确获取文件的MIME类型。通过读取文件并调用此API,可以实现根据文件路径确定其MIME类型。
摘要由CSDN通过智能技术生成

首先,什么是MIME,是不是文件的后缀名呢?

当然不是。

有时候我们需要获取某个文件的后缀名,这也许对你来说太小case了,你可能不加思考的写了一个函数,更加文件名字符串查找最后一个’.’,然后取最有一个’.’之后的字符串,即为我们要得到的后缀名。

看似非常完美,但确实漏洞百出。

如果我的文件没有后缀名怎么办?
如果我的一张png图片,我强制把后缀名改为jpg怎么办?
这样你根据文件名字方法就不能获得百分百正确的后缀名。

所以,就该MIME出场了!

何为MIME?

MIME (Multipurpose Internet Mail Extensions) 是描述消息内容类型的因特网标准。
MIME 消息能包含文本、图像、音频、视频以及其他应用程序专用的数据。

接下来的工作就是在windows系统上,如何根据一个文件名路径,获取这个文件的mime呢?

起初,我觉得应该找一个第三方库来实现这个小小的功能,比如libmagic。

但是暮然回首,发现windows为我们提供了api。这里要插一句:windows确实是最复杂的操作系统。有时候我们再忽略了太多windows api给我们提供的函数。

FindMimeFromData
作用:
Determines the MIME type from the data provided.
原型:

HRESULT FindMimeFromData(
             LPBC    pBC,
             LPCWSTR pwzUrl,
             LPVOID  pBuffer,
             DWORD   cbSize,
             LPCWSTR pwzMimeProposed,
             DWORD   dwMimeFlags,
             LPWSTR  *ppwzMimeOut,
  _Reserved_ DWORD   dwReserved
);

参数:

pBC
A pointer to the IBindCtx interface. Can be set to NULL.
pwzUrl
A pointer to a string value that contains the URL of the data. Can be set to NULL if pBuffer contains the data to be sniffed.
pBuffer
A pointer to the buffer that contains the data to be sniffed. Can be set to NULL if pwzUrl contains a valid URL.
cbSize
An unsigned long integer value that contains the size of the buffer.
pwzMimeProposed
A pointer to a string value that contains the proposed MIME type. This value is authoritative if type cannot be determined from the data. If the proposed type contains a semi-colon (;) it is removed. This parameter can be set to NULL.

下面看看如何应用,首先是读一个文件,然后调用FindMimeFromData函数即可:

#include <urlmon.h>
#include <stdio.h>
#include <Windows.h>
#include <iostream>
#pragma comment(lib, "Urlmon.lib")

int main(int argc, char* argv[])
{
    char buff[256];
    LPWSTR out;

    FILE *in = fopen("D:\\libsakura.lib", "rb");

    fread(buff, 1, 256, 
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一苇渡江694

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值