使用二进制模式读取文件的扩展名 [英] read the extension of file using binary mode

查看:249
本文介绍了使用二进制模式读取文件的扩展名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道文件名甚至在重命名之后。



例如我将.jpeg更改为.txt然后如何使用header找到该扩展名。

i wanted to know the file name even after renaming.

for example i changed .jpeg to .txt then how can find that extension using header.

推荐答案

您正在Linux上寻找类似 file 命令的东西,并带有 magic 数据文件。



如果您只想识别一些图像文件类型,只需从文件开头读取一些字节并检查它们是否有图像文件特定序列:



You are looking for something like the file command on Linux with it''s magic data file.

If you only want to identify a few image file types, just read some bytes from the begin of the file and check them for image file specific sequences:

const char *lpszType = NULL;
char pBuffer[16] = "";
FILE *f = fopen(lpszFile, "rb");
if (f)
{
    fread(pBuffer, 1, 16, f);
    if (0 == memcmp(pBuffer, "BM", 2) && 0 == memcmp(pBuffer + 6, "\0\0\0", 4))
        lpszType = "BMP";
    else if (0 == strcmp(pBuffer, "II*") || 0 == strcmp(pBuffer, "MM*"))
        lpszType = "TIFF";
    else if (0 == memcmp(pBuffer, "\x89PNG\r\n\x1A\n", 8))
        lpszType = "PNG";
    else if (0 == memcmp(pBuffer, "GIF87a", 6) || 
        0 == memcmp(pBuffer, "GIF89a", 6))
        lpszType = "GIF";
    else if (0 == memcmp(pBuffer, "\xFF\xD8\xFF", 3) && 
        pBuffer[3] >= 0xE0 && pBuffer[3] <= 0xEF &&
        4 == strlen(pBuffer + 6))
        lpszType = "JPEG";
    fclose(f);
}


听起来好像你的意思是你想要找出文件的内容是什么,无论文件名和延期。为了做到这一点,你需要研究各种文件格式规范。



Wrt JPEGs,所有JPEG总是以十六进制FF D8(ASCIIÿØ)开头 - 其余的是包装具体。您可以自己搜索规范。但是,我确实发现这个方便的页面有很多不同的文件格式标识符(虽然我不能保证准确性),包括一组各种JPEG格式标题: http://www.garykessler.net/library/file_sigs.html [ ^ ]



问候,

Ian。
It sounds as if you mean that you want to be able to find out what the content of a file is, regardless of filename and extension. In order to do so you would need to research various file format specifications.

Wrt JPEGs, all JPEGs always begin with hexadecimal FF D8 (ASCII ÿØ) - the rest is wrapper specific. You can search for the specification yourself. However, I did find this handy page with a lot of different file format identifiers (though I cannot guarantee the accuracy) including a set of various JPEG format headers: http://www.garykessler.net/library/file_sigs.html[^]

Regards,
Ian.


无法完成。执行此类操作的唯一方法是在重命名文件之前记录文件名并查看缓存的值。
It can''t be done. The only way to do this kind of thing is to record the filename before it is renamed and look at the cached value.


这篇关于使用二进制模式读取文件的扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆