0

So the do/while loop is infinite, as I have been told before. Is there a better way to implement this loop?

typedef uint8_t BYTE;

int main(void)
{

FILE* file = fopen("card.raw", "r");
if (file == NULL)
{
    printf("Doesnt work dog\n");
    return 1;
}

FILE* img = NULL;
int jpgnum = 1;
BYTE buffer[512];
//read until first jpg
do
{
    BYTE buffer[512];
    fread(buffer, sizeof(buffer) , 1, file);
}
while (buffer[0] != 0xff && buffer[1] != 0xd8 && buffer[2] != 0xff && (buffer[3] != 0xe0 || buffer[3] != 0xe1));

while (!feof(file))
{
   BYTE buffer[512];
   char jpgname[8];

   // finding a new jpg
   if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
   {
        if (img != NULL)
        {
            fclose(img);
        }
        sprintf(jpgname, "%03d.jpg", jpgnum);
        img = fopen(jpgname, "w");
        jpgnum++;
        fwrite(buffer, sizeof(buffer), 1, img);
   }
fwrite(buffer, sizeof(buffer), 1, img);    
}
fclose(img);
fclose(file);
return 0;
}

1 Answer 1

0

Your question is "Is there a better way to implement this loop?"

Your first loop is going into an infinite loop, but I suspect you haven't figured out the cause. Look at this section of code:

BYTE buffer[512];
//read until first jpg
do
{
    BYTE buffer[512];
    fread(buffer, sizeof(buffer) , 1, file);
}
while (buffer[0] != 0xff && buffer[1] != 0xd8 && buffer[2] != 0xff 
       && (buffer[3] != 0xe0 || buffer[3] != 0xe1));

The problem is that you have redeclared buffer[512] inside the loop. Since it's inside a set of curly braces, it doesn't trigger a compile error, but it does override the original declaration of buffer. The problem is that the fread is loading the inner buffer, but the while loop is testing the outer one. Since the outer one is never loaded from fread, and is never changed, it will never show a jpg signature.

If you delete the buffer declaration statement inside the while loop, it will cure the infinite loop.

However, there are other issues to be dealt with. I'll leave it to you to work on them.

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

2
  • Thanks for the help. I am having a lot of trouble on this one, so I may just rewrite the entire thing at a later date, and keep moving on with the class.
    – Fijj
    Commented Sep 8, 2015 at 22:31
  • Also your condition is wrong. Check this answer: cs50.stackexchange.com/a/12264/7539
    – ChrisG
    Commented Sep 9, 2015 at 6:39

You must log in to answer this question.

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