gpt4 book ai didi

c - 如何正确打印 JPEG 文件的字节? - CS50 PSET3 恢复

转载 作者:行者123 更新时间:2023-11-30 14:33:21 25 4
gpt4 key购买 nike

我正在尝试对包含多个 JPEG 的文件使用 fread 并将 JPEG 写入新文件,但在执行此操作之前,我需要正确查看该文件并根据其第一个字节查找 JPEG if 语句位于下面代码的底部。

我无法进入 if 语句,并一直尝试打印出字节,但在打印时遇到了问题。

我希望只打印缓冲区的 0 字节,但我的输出如下所示:711151a6cec117f07603c9a973599166

我对 C 和 fread 非常陌生,如果有任何帮助,我们将不胜感激!

代码:

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
// Check for 2 arguments, the name of the program and the file being read
if (argc != 2)
{
printf("Usage: ./recover image\n");
return 1;
}
else
{
//Open the file
FILE * fp;
fp = fopen(argv[1], "r");

//Get file length
fseek(fp, 0, SEEK_END);
int f_length = ftell(fp);
fseek(fp, 0, SEEK_SET);

// If not file is found then exit
if(fp == NULL)
{
printf("File not found\n");
return 2;
}

// Allocate buffer for fread function
int *buffer = (int*)malloc(f_length);
if (buffer == NULL)
{
printf("Buffer is null\n");
return 1;
}

// Read thorugh the file
while(fread(buffer, 512, 1, fp) == 1)
{


for (int i = 0; i < 1; i++)
{
printf("%x\n", buffer[i]);
}

if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
printf("Found a jpg\n");
}
}

// Exit the program
return 0;
}
}

最佳答案

int *buffer 不正确,因为其目的是处理字节而不是整数。如果使用 int *,则 buffer[0] 将是前 4 个字节,而不是预期的第一个字节。将其更改为unsigned char *buffer

所以明确地,该行应该如下(包括删除不必要的强制转换):

unsigned char *buffer = malloc(f_length);

关于c - 如何正确打印 JPEG 文件的字节? - CS50 PSET3 恢复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59384556/

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