gpt4 book ai didi

c - 读取二进制文件并确定文件类型的程序

转载 作者:行者123 更新时间:2023-11-30 18:23:30 26 4
gpt4 key购买 nike

我编写了这段代码,它读取文件二进制并确定其文件类型(用于一些测试文件结尾)。它适用于 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,因此您会在值上获得符号扩展。

显然,内置魔术签名表也应该是 const unsigned char,并且应该通过单个 memcmp() 调用进行比较。

关于c - 读取二进制文件并确定文件类型的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54905059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com