0

I reviewed my code 10 times and still not know why it gives segmentation fault when I run , I could use a help of an expert , thanks in advance.

 #include <cs50.h> 
 #include <stdio.h>
 #include <stdlib.h>
 #define BUFFER_SIZE 512
 int main (void) {


//open card for reading
FILE *inptr = fopen ("card.raw" , "r");

if (inptr == NULL)
{
    fclose(inptr);
    fprintf(stderr, "Could not create \n");
    return 1;
}

unsigned char Data[BLOCK_SIZE];

//integer A to make sure we have an opened JPEG to start writing
int A = 0;

int Name_Count = 0 ;

FILE *JPEG = NULL;



//While loop to iterate between blocks of 512 bytes
while (fread(Data, BLOCK_SIZE , 1, inptr) == 1)

{

//reading inside the block of 512 bytes
//fread (&Data , 512 , 1 , inptr);



if ( Data[0] == 0xff && Data[1] == 0xd8 && Data[2] == 0xff && (Data[3] & 0xe0) == 0xe0)
{

A++ ;

//close the old file
fclose (JPEG);

char JPEG_Name[8];

sprintf(JPEG_Name, "%03d.jpg", Name_Count);

//Open a new file
JPEG = fopen(JPEG_Name, "a");

Name_Count ++;

}


    if ( A >= 1 )
        {
        //write data to already opened JPEG file
        fwrite(Data , BLOCK_SIZE  , 1 , JPEG);
        }


}



fclose (inptr);
fclose (JPEG);

 }

2 Answers 2

1

There are a couple of problems with the code posted above. First, it needs to check Data[3], not buffer[3].

The seg fault occurs later. fclose (JPEG); will trigger a seg fault if JPEG equals NULL, i.e., the first file hasn't been opened.

That should get you going.

If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • THANKS for Ur Help , Noted. and now my code works perfectly. Commented Jun 6, 2018 at 19:56
0

After reviewing it again I realized I just need to edit what is inside the IF condition

if ( Data[0] == 0xff && Data[1] == 0xd8 && Data[2] == 0xff && (Data[3] & 0xe0) == 0xe0 )
{

A++ ;

if (A >=2)
{
//close the old file if any
fclose (JPEG);
}

//array for JPEG Names
char JPEG_Name[8];

//to print the name of the new file
sprintf(JPEG_Name, "%03d.jpg", Name_Count);

//open new file for writing
JPEG = fopen(JPEG_Name, "a");

Name_Count ++;

}
1
  • No, that just deleted the check of the 4th byte. See my answer.
    – Cliff B
    Commented Jun 4, 2018 at 4:36

You must log in to answer this question.

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