I have a problem where I need to check if I have an open file on my loop, so I properly close the previous file before writing a new one. But my check only works if I fclose(img) if my counter > 0. The problem here is that (img) is not actually declared until after the check, but if I put it above the check it renders the check pointless. How do I reformat this code so that I can fclose(img) if my counter > 0, while also declaring img before the counter somehow?
do
{
unsigned char read[512];
fread(&read, 512, 1, memcard);
if (read[0] == 0xff && read[1] == 0xd8 && read[2] == 0xff && (read[3] & 0xf0) == 0xe0)
{
if(counter > 0)
{
fclose(img);
}
counter++;
sprintf(filename, "%03i.jpg", counter);
FILE *img = fopen(filename, "w");
}
if (counter > 0)
{
fwrite(&read, 512, 1, img);
}
readNum = fread(&read, 512, 1, memcard);
}
while (readNum == 512);
Edited Code
int counter = 0; // Initialize counter for .jpgs found
char *filename = NULL;
FILE *img = NULL;
unsigned char read[512];
while (fread(&read, 1, 512, memcard) == 512)
{
//unsigned char read[512];
//fread(&read, 1, 512, memcard);
if (read[0] == 0xff && read[1] == 0xd8 && read[2] == 0xff && (read[3] & 0xf0) == 0xe0)
{
if(counter > 0)
{
fclose(img);
}
counter++;
sprintf(filename, "%i.jpg", counter);
img = fopen(filename, "w");
}
if (counter > 0)
{
fwrite(&read, 1, 512, img);
}
}