0

I've some issues with my code, it compiles but it gets stuck in an infinite loop. I've run gdb and apparently it never finds the start of a jpg.

here is a snippet:(UPDATE here is the rest of the code)

I changed the fread in the while loop for fgetc but it is still running forever

int main(int argc, char* argv[]) { if (argc != 1) { printf("executing should not have additional input!"); }

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

while (fgetc(inptr) != EOF)    {

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

fread(&data, 512, 1, inptr);
    if(data[0] == 0xff && data[1] == 0xd8 && data[2] == 0xff && (data[3]==0xe0 || data[3]==0xe1))
            {

                        jpeg = true;
                        found += 1;
                    }


if (jpeg == true)
{
    //it only executes once it has found a new jpeg
    if (position == found -1)
    {
        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;

}

2
  • The code should not cause an infinite loop, the only problem i see is that you are calling fread() two times before checking the beginning of the jpeg on every iteration, you should remove the second fread() and leave only the one inside the loop condition. But this should not cause an infinite loop. Maybe there is something else inside the loop causing it.
    – wallek876
    Jul 26 '15 at 6:58
  • I changed the while to a fgetc condition but it is still weird :( Jul 27 '15 at 4:45
1

You are reading two 512 byte blocks of data before you do anything with them, so every odd block of data is simply thrown away (or worse, depending on the rest of the code.) If all of the signatures fall on odd numbered blocks, it's possible that you would never see them. Or, there could be something else wrong in the code that we haven't seen.

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

As for the loop, there's no telling what's going on without seeing the rest of the while loop code.

2
  • I see, i changed it so that it wouldn't read two, but still it is going forever Jul 27 '15 at 4:42
  • All that accomplished was to replace one problem with another. Now, you read 1 character followed by reading 512 bytes, so you're reading 513 bytes on each pass which throws everything off. You need to completely eliminate one of the two original reads.
    – Cliff B
    Jul 27 '15 at 5:05

You must log in to answer this question.

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