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

如何正确打印JPEG文件的字节CS50 PSET3恢复,c,fread,cs50,C,Fread,Cs50,我试图在一个包含多个JPEG的文件上使用fread,并将JPEG写入新文件,但在此之前,我需要正确地查看该文件,并根据下面代码底部的if语句,根据JPEG的第一个字节查找JPEG 我无法进入if语句,一直在尝试打印字节,但在打印时遇到了问题 我希望只打印缓冲区的0字节,但我的输出如下所示: 711151a6 CEC17F0 7603c9a9 73599166 我是C和fread的新手,任何帮助都将不胜感激 代码: #包括 #包括 int main(int argc,char*argv[]) {

我试图在一个包含多个JPEG的文件上使用fread,并将JPEG写入新文件,但在此之前,我需要正确地查看该文件,并根据下面代码底部的if语句,根据JPEG的第一个字节查找JPEG

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

我希望只打印缓冲区的0字节,但我的输出如下所示: 711151a6 CEC17F0 7603c9a9 73599166

我是C和fread的新手,任何帮助都将不胜感激

代码:

#包括
#包括
int main(int argc,char*argv[])
{
//检查2个参数,程序名和正在读取的文件
如果(argc!=2)
{
printf(“用法:./recover image\n”);
返回1;
}
其他的
{
//打开文件
文件*fp;
fp=fopen(argv[1],“r”);
//获取文件长度
fseek(fp,0,SEEK_END);
int f_length=ftell(fp);
fseek(fp,0,SEEK_集);
//如果未找到文件,则退出
如果(fp==NULL)
{
printf(“未找到文件”);
返回2;
}
//为fread函数分配缓冲区
int*buffer=(int*)malloc(f_长度);
if(buffer==NULL)
{
printf(“缓冲区为空\n”);
返回1;
}
//仔细阅读文件
while(fread(缓冲区,512,1,fp)==1)
{
对于(int i=0;i<1;i++)
{
printf(“%x\n”,缓冲区[i]);
}
如果(缓冲区[0]==0xff&&buffer[1]==0xd8&&buffer[2]==0xff&&buffer[3]&0xf0)==0xe0)
{
printf(“找到一个jpg\n”);
}
}
//退出程序
返回0;
}
}

int*缓冲区
不正确,因为其目的是处理字节而不是int。如果使用了
int*
,则例如,
buffer[0]
将是前4个字节,而不是预期的第一个字节。将其更改为
无符号字符*缓冲区

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


请看下面我的答案。当我对您的代码进行这些更改时,它使用了一个测试JPG文件。但是,调试数据表明可能存在其他问题。但是让我知道这是怎么回事。
intf_length=ftell(fp)是错误的。请参见--
type
返回什么?。如果你有长度,你
malloc(f_长度)
(不要强制转换malloc的返回值),那么为什么要
while(fread(buffer,512,1,fp)==1)
而不是
if(fread(buffer,lenfth,1,fp)!=1){/*handle error*/}
?正如@kaylum所解释的,您需要
无符号字符*缓冲区
not
int*
…可能还想指出其他问题,并解释没有必要强制执行malloc
的返回,这是不必要的。请参阅:
else
是多余的,它只是添加了不必要的缩进。您已经在
if
块中返回了
#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;
    }
}
unsigned char *buffer = malloc(f_length);