0

My code keeps giving a segmentation fault when I run it. I figure it has something to do with my jpg array, but I'm not sure. Thanks in advance for any help!

Here's my code:

/**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */

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


#define FAT 512
typedef uint8_t BYTE;


int main(int argc, char* argv[])
{
    //open card
    FILE* file = fopen("card.raw", "r");
    if (file == NULL)
    {
        printf("Could not open file\n");
        return 1;
    }
    FILE* img;
    //declare buffer
    BYTE buffer[FAT] = {0};

    //array of JPGS
    char jpg[50];

    //counter for JPGs
    int numPics = 000;


    //repeat until end of card
    while (fread(&buffer, sizeof(buffer), FAT, file) != FAT)
    {
        //read file in 512 block increments
        int times = 0;
        fseek(file, (512*times), SEEK_SET);
        fread(&buffer, sizeof(buffer), 512, file);
        times++;

        //checks if is JPG
        int counter = 0;
        for (int i=0; i<4; i++)
        {
           char key[4] = {0xff, 0xd8, 0xff, 0xe};
           if (fread(&buffer, sizeof(buffer), 1, file) == key[i])
           {
               counter++;
           }
        }
        if (counter==4)
        {
            //closes image file if open
            if (numPics!=000)
            {
                fclose(img);
            }
            //copy into new file
            sprintf(jpg, "%d.jpg", numPics);
            img = fopen(jpg, "a");
            if (img == NULL)
            {
                printf("Error! Could create the file!\n");
                return 1;
            }
            fwrite(&buffer, sizeof(buffer), FAT, img);
            numPics++;

        }
        else
        {
            //write into currrent file
            if (numPics!=000)
            {
               fwrite(&buffer, FAT, FAT, img); 
            }
        }

    }




    fclose(img);            

    //end of file close remaining files




}
0

There were quite a few things I had to change to get it to work. Instead of relying of fseek() to get the pointer in the right place, whenever I called fread, I used %buffer[0] for the struct.

Also I used a for loop and read each byte of file to buffer. I think that fixed the segmentation fault.

I changed more things, but those two were the most important.

1
  • edit: check50 isn't working – ebhc Jun 29 '16 at 16:57

You must log in to answer this question.

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