0

I'm making a program for my programming class where I have to recover JPG files from another file and store them into their own separate files. The code compiles just fine, but when I run it, I get a segmentation fault and can't seem to find where it happens.

    bool firstJpeg = true;
    char *jpeg;
    int jpegCount = 0;
    char *jpegName = NULL;
    FILE *newJpeg;

    // I think it's happening somewhere in the following block of code

    // read file until EOF

    while (feof(file) == false)
    {

        if (firstJpeg == true) 
        {
            if (checkJpeg(file)) 
            {
                fseek(file, -4, SEEK_CUR); //brings cursor back 4 bytes
                firstJpeg = false;
                jpegCount++;
                sprintf(jpegName, "00%d.jpg", jpegCount); // makes a name for the new jpeg file
                puts(jpegName);
                newJpeg = fopen(jpegName, "w"); // opens new jpeg file
                jpeg = malloc(sizeof(char) * 512); // allocates 512 bytes
                fread(jpeg, 512, 1, file); // reads 512 bytes
                fwrite(jpeg, 512, 1, newJpeg); // writes 512 bytes into the new jpeg file

            }
            else
            {
                fseek(file, 508, SEEK_CUR); // skips the next 508 bytes
            }
        }
Andy_V
  • 27
  • 5

0 Answers0