我写了这段代码,它读取文件二进制文件并确定其文件类型(对于一些测试文件的目的)。它适用于PDF,MP3但不适用于jpg。
问题是什么?对于jpg,行printf("%s[%d]: %x\n", "Buffer", j, buffer[j]);
显示多个字节(即ffffff而不是仅一个字节)
#include <stdio.h>
const int header[6][8] = {
{0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A},
{0xFF,0xD8,0x00,0x00,0x00,0x00,0x00,0x00},
{0xFF,0xFB,0x00,0x00,0x00,0x00,0x00,0x00},
{0x49,0x44,0x33,0x00,0x00,0x00,0x00,0x00},
{0x25,0x50,0x44,0x46,0x2D,0x00,0x00,0x00},
{0x42,0x4C,0x45,0x4E,0x44,0x45,0x52,0x00}
};
const char* filetype[6] = {"PNG","JPG","MP3","MP3v2","PDF","Blender"};
int main()
{
FILE *fd;
char buffer[8];
if ((fd = fopen("C:\\Users\\***\\Desktop\\Unnamed.jpg", "rb")) == NULL) {
return -1;
}
//fread(buffer, sizeof(char), 8, fd);
fread(buffer, sizeof(buffer), 1, fd);
for (int i = 0; i < 6; i++) {
for(int j = 0; j < 8; j++){
printf("%s[%d][%d]: %x\n","Header",i,j,header[i][j]);
printf("%s[%d]: %x\n", "Buffer", j, buffer[j]);
if (header[i][j] == 0x00) {
printf("%s: %s","Found file type",filetype[i]);
return 1;
}
if (header[i][j] != buffer[j]) {
break;
}
}
}
printf("%s", "Couldn't determine filetype - Not in library");
return 0;
}
使用unsigned char
为buffer
(你也可以为header
)以避免问题,如果你的char
被签名并给出一个负值(你比较int如0x89,其中第7位被设置)
你也有PNG的问题,因为PNG的值是:
{0x89,0x50,0x4E,0x47,0x0D,的0x0A,0x1A的,的0x0A}
没有像所有其他情况那样以0结尾,这是必需的,因为您的算法需要找到0来表示您找到了:
if (header[i][j] == 0x00) {
printf("%s: %s","Found file type",filetype[i]);
return 1;
}
只需为PNG添加一列也为0。
最后:
const unsigned char header[6][9] = {
{0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A, 0x00},
{0xFF,0xD8,0x00,0x00,0x00,0x00,0x00,0x00, 0x00},
{0xFF,0xFB,0x00,0x00,0x00,0x00,0x00,0x00, 0x00},
{0x49,0x44,0x33,0x00,0x00,0x00,0x00,0x00, 0x00},
{0x25,0x50,0x44,0x46,0x2D,0x00,0x00,0x00, 0x00},
{0x42,0x4C,0x45,0x4E,0x44,0x45,0x52,0x00, 0x00}
};
const char* filetype[6] = {"PNG","JPG","MP3","MP3v2","PDF","Blender"};
int main()
{
FILE *fd;
unsigned char buffer[sizeof(header[0])];
if ((fd = fopen("C:\\Users\\***\\Desktop\\Unnamed.jpg", "rb")) == NULL) {
return -1;
}
fread(buffer, sizeof(buffer), 1, fd);
for (int i = 0; i < ; i++) {
for(int j = 0; j < sizeof(header[0]); j++){
printf("%s[%d][%d]: %x\n","Header",i,j,header[i][j]);
printf("%s[%d]: %x\n", "Buffer", j, buffer[j]);
if (header[i][j] == 0x00) {
printf("%s: %s","Found file type",filetype[i]);
return 1;
}
if (header[i][j] != buffer[j]) {
break;
}
}
}
printf("%s", "Couldn't determine filetype - Not in library");
return 0;
}
你忘了制作你的缓冲区unsigned char
,所以你得到了值的符号扩展。
显然,内置魔法签名表也应该是const unsigned char
,并且应该用单个memcmp()
调用进行比较。