0

I was trying to complete the recover problem and it's giving me a segmentation fault. Any help would be appreciated.

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

#include "bmp.h"

int main(int argc, char *argv[])
{
    // ensure proper usage
    if (argc != 2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }

    // remember filenames
    char *infile = argv[1];

    // open input file
    FILE *inptr = fopen(infile, "r");
    if (inptr == NULL)
    {
        printf("Could not open %s.\n", infile);
        return 2;
    }

    BYTE space[512];
    char filename[10];
    FILE *outptr = NULL;
    int imgCount = 0;
    bool search = true;

    while(search == true)
    {
        size_t read = fread(space, sizeof(BYTE), 512, inptr);

        if (feof(inptr))
        {
            search = false;
        }

        if (space[0] == 0xff && space[1] == 0xd8 && space[2] == 0xff && (space[3] & 0xf0) == 0xe0b)
        {
            if (outptr != NULL)
            {
                fclose(outptr);
                imgCount++;
            }
            else
            {
                outptr = fopen(filename, "w");
                sprintf(filename, "%03i.jpg", imgCount);
                fwrite(space, sizeof(BYTE), read, outptr);
            }
        }
        else
        {
            outptr = fopen(filename, "w");
        }

    }

    // close outfile
    fclose(outptr);

    // close infile
    fclose(inptr);

    // success
    return 0;
}
1
  • Have you determined which line is causing the seg fault? – Cliff B Oct 26 '19 at 21:05
0

What happens if the buffer is not a signature? Why do you want to open a file every time, even before you've ever found the first jpg?

1
  • Hi. I solved my problem. Thank you! – Julk Nov 1 '19 at 14:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .