0

I have been trying to edit this code multiple times and keep getting a segmentation fault.

I've tried debug50 and narrowed down the incorrect line to be on line 53

fwrite(block,sizeof(int),512,image)

I do not see where I'm wrong. I'm just hoping someone can help me. Thanks. :-D

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

int newjpeg=0,jpeg=0;
typedef uint8_t BYTE;
BYTE block[512];
//When newjpeg==0,jpeg is start of jpeg
//jpeg counts how many jpeg have been opened
char *filename=NULL;
FILE* image;
int main(int argc, char *argv[])

{

    if (argc!=2)
    {
        printf("Usage: ./recover image\n");
        return 1;
    }
    else
    {
        FILE *file=fopen(argv[1],"r");
        if (file==NULL)
        {
            printf("Invalid file\n");
            return 1;
        }
        else
        {
            while (fread(block,sizeof(BYTE),512,file)==512)
            {
                if (block[0]==0xff && block[1]==0xd8 && block[2]==0xff && (block[3] & 0xf0)==0xe0)
                {
                    if (newjpeg==0)
                    {
                        sprintf(filename,"%03i.jpeg",jpeg);
                        image= fopen(filename,"w");
                        fwrite(block,sizeof(BYTE),512,image);
                        newjpeg++;
                        jpeg++;
                    }
                    else
                    {
                        fclose(image);
                        sprintf(filename,"%03i.jpeg",jpeg);
                        image= fopen(filename,"w");
                        fwrite(block,sizeof(BYTE),512,image);
                    }
                }
                else
                {
                    image= fopen(filename,"w");
                    fwrite(block,sizeof(BYTE),512,image);
                }
            }
            fwrite(block,sizeof(BYTE),fread(block,sizeof(BYTE),512,file),image);
            fclose(file);
            return 0;
        }
    }
}
-1

Instead of write, use append. Also remove the last fwrite. Instead fclose the last image. Don't use the fopen in the else inside else.

If this helped, please click the tick mark.

You must log in to answer this question.

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