Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

c - Keep getting segmentation fault while trying to write a program that breaks down a file into multiple JPGs

As the title says, I've been trying to write a program in C that turns a file into multiple JPGs for a CS exercise. I've closed and freed everything I've worked with, but I'm still getting a segmentation fault, and I'm not quite sure why. Any advice wold be of great help.

EDIT I already found the answer, it's the fact that there's a possibility that the first block of bytes has no header, which makes the program go to the "else" conditional and write 512 bytes of nothing into a file that doens't exist. The solution was to turn else into else if (block[0] != 0xff && block[1] != 0xd8 && block[2] != 0xff && (block[3] & 0xf0) != 0xe0 && filenumber != 0) Hopefully this helps somebody!

typedef uint8_t BYTE;

int main(int argc, char *argv[])
{
    // Checks for correct argv usage
    if (argc != 2)
    {
        printf("Usage: filter [file]
");
        return 1;
    }

    FILE *f = fopen(argv[1], "r");
    if (f == NULL)
    {
    printf("Invalid file
");
    return 1;
    }

    int filenumber = 0;
    BYTE *block = malloc(512 * sizeof(BYTE));

    char *filename = NULL;
    FILE *img = NULL;
    while (fread(&block, sizeof(BYTE), 512, f) == 512)
    {
        if (block[0] == 0xff && block[1] == 0xd8 && block[2] == 0xff && (block[3] & 0xf0) == 0xe0)
        {
             if (filenumber == 0)
             {
                filename = malloc(8);
                sprintf(filename, "%03i.jpg", filenumber);
                img = fopen(filename, "a");
                if (img == NULL)
                return 1;

                fwrite(&block, sizeof(BYTE), 512, img);
                filenumber++;
             }
             else
             {
                 fclose(img);
                 sprintf(filename, "%03i.jpg", filenumber);
                 img = fopen(filename, "a");

                 if (img == NULL)
                 return 1;

                 fwrite(&block, sizeof(BYTE), 512, img);
                 filenumber++;
             }
        }
        else
        {
            fwrite(&block, sizeof(BYTE), 512, img);
        }
    }

        fwrite(&block, sizeof(BYTE), fread(block, sizeof(BYTE), 512, f), img);
        free(filename);
        free(block);
        fclose(img);
        fclose(f);
        return 0;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...