0

I wanted to finish the psets I left behind throughout the course...I still want to, even if it is not in this year, I just don't know why my code isn't detecting the jpg signatures, it goes on an infinite loop.

And I don't even know why it isn't at least ending, because the loop should end once card.raw finishes to exist, and then return 0 (but it doesn't).

I asked something similar before, I now call fread only once, as suggested in the answers, but still. I've read other questions similar to these, but still. Help. Pleaase.

AND HAPPY HOLIDAYS

code:

int main(void)
{
FILE* inptr = fopen("card.raw", "r");
int found = 0;
int position = 0;
bool jpeg = false;
uint8_t data[512];
char title[8];
FILE* image;

while (fread(&data, 512, 1, inptr) == 1)
{

// reads the file and checks if it is the beginning of a jpeg   




    if(data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff && (data[3]==0xe0 || data[3]==0xe1))
            {

                        jpeg = true;
                        found += 1;
                    }

//always executes once it has found the first jpg
    if (jpeg == true)
    {
    //it only executes once it has found a new jpeg
    if (position == found -1)
    {
        if(image != NULL)
        {
        fclose(image);
        }

        if (found <= 10)
            {                
            sprintf (title, "00%d.jpg", found-1);
            image = fopen(title, "w");
            }
        else
            {
            sprintf (title, "01%d.jpg", found-11);
            image = fopen(title, "w");
            }        


        position ++;
    }

    fwrite(&data, 512, 1, image);

}


}


//closing files
fclose(inptr);
fclose(image);

//the end
return 0;



 }

1 Answer 1

1

Interesting. When I run your code, I see that it detects the first signature and then seg faults. It does not enter an infinite loop. Look at the following:

FILE* image;
...
if(image != NULL)
{
    fclose(image);
}

What do you think is in image after it is created?

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

2
  • Did I mention that the seg fault is from trying to close a file (image) that was never opened?
    – Cliff B
    Commented Jan 1, 2016 at 4:39
  • I'm about to cry Cliff B !!! thank you sooo much that was it ! <3 Commented Jan 9, 2016 at 18:20

You must log in to answer this question.

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