My first time posting on the forum so hope someone can help. I've been scratching my head over this code for a while now and can't understand why I get the undeclared identifier! My code seems to follow logically what I expect but here's my walk through with the actual code beneath:
While not end of file
Load 512 bytes into array
Check first four array elements for JPG header
IF JPG and it is for the first time
create filename 000.jpg
open file and write data
increment jpg counter
ELSE NOT FIRST JPG
close previous file
create new filename 001.jpg
open file and write data
increment jpg counter
**** CODE EXTRACT ****
BYTE buffer[BLOCK_SIZE]; // create an array BLOCK_SIZE big
// read BLOCK_SIZE worth of bytes into buffer
while (fread(buffer, sizeof(BYTE), BLOCK_SIZE, infile) == BLOCK_SIZE)
{
// check if first four bytes of blockare JPG header
if (buffer[0]==0xFF && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// check if this is the first time a header has been found
if (jpgcount == 0)
{
// first time JPG has been found
// create filename
sprintf(filename, "%03i.jpg", jpgcount);
// open file
FILE *img = fopen(filename, "w");
if (img == NULL)
{
printf("Could not open file.\n");
return 3;
}
printf("first header! jpgcount: %d\n", jpgcount); //debug
// write data to file
fwrite (buffer, sizeof(BYTE), BLOCK_SIZE, img);
// increment jpgcount
jpgcount++;
}
else
{
// not first JPG
// close previous file
fclose (img);
// create new filename
sprintf(filename, "%03i.jpg", jpgcount);
// open file
FILE *img = fopen(filename, "w");
if (img == NULL)
{
printf("Could not open file.\n");
return 3;
}
printf("new header! jpgcount: %d\n", jpgcount); //debug
// write data to file
fwrite (buffer, sizeof(BYTE), BLOCK_SIZE, img);
// increment jpgcount
jpgcount++;
}
}
I haven't explained rest of my code as the issue seems to be with the fclose in the else associated with the header check. The compiler is saying fclose(img) 'img' is undeclared, however this part of the loop won't be reached unless JPG counter is greater than 1 AND a valid header has been found. In which case the first IF will have already been executed and the file open?
The hints video suggests fclose in the way I've done it should be okay, and I've seen other examples but can't figure out what this bug is. Been stuck on this now for a couple of weeks.
Any help most appreciated, thankyou!!
Jon