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

问题描述 投票:0回答:1

我正在尝试对包含多个JPEG的文件使用fread并将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;
    }
}
c fread cs50
1个回答
1
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.