segfault:恢复无法正确读取卡?

时间:2020-10-02 10:47:49

标签: c cs50

该pset4程序应该从输入文件中恢复jpeg。它一次读取512个字节,检查新jpeg的开始并将每个新jpeg写入新文件。

它可以正确编译,但是在尝试运行它时却出现了段错误。我使用了调试器,看来问题在于程序未按我期望的那样读取buffer。在第一个if循环之前使用printf,我发现buffer[0]buffer[4]个存储的字符而不是字节。有关如何解决此问题的任何建议?

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

typedef uint8_t BYTE;
#define BUFFER_SIZE 512

int main(int argc, char *argv[])
{
    // Ensure proper number of arguments
    if (argc != 2)
    {
        printf("Usage: only one argument allowed.\n");
        return 1;
    }

    // Open input file
    FILE *card = fopen(argv[1],"r");

    // Ensure input file open properly
    if (card == NULL)
    {
        printf("Could not open %s.\n", argv[1]);
        return 1;
    }
    
    BYTE buffer[BUFFER_SIZE];
    FILE *img = NULL;
    int jpegCounter = 0;
    char *filename = NULL;

    while ((fread(buffer, BUFFER_SIZE, 1, card) != 0))
    {
        fread(buffer, BUFFER_SIZE, 1, card);
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
        {
            if (jpegCounter == 0)
            {
                sprintf(filename, "%03i.jpg", jpegCounter);
                img = fopen(filename,"w");
                fwrite(buffer, BUFFER_SIZE, 1, img);
                jpegCounter++;
            }
            else
            {
                fclose(img);
                sprintf(filename, "%03i.jpg", jpegCounter);

                img = fopen(filename,"w");
                fwrite(buffer, BUFFER_SIZE, 1, img);
                jpegCounter++;
            }

        }
        else
        {
            fwrite(buffer, BUFFER_SIZE, 1, img);
        }

    }
    
    // Close last .jpeg
    fclose(img);
    
    // Close card
    fclose(card);
    
    // Success
    return 0;
}

0 个答案:

没有答案