In the walkthrough Zamyla mentions using fread as a condition. I've tried using it as the while condition, hoping the loop would stop when fread returns 0 but I get only 26 heavily distorted jpegs after running this program. I have created a working code using a forever loop and feof but I was trying to do it this way as well and can't figure out what the issue. Here is the relevant code:
int count = 0; BYTE buffer[512];
while ((fread(buffer, 512, 1, image)) != 0 )
{
// iterate over each byte in each block until you reach the end of the file
for (int i = 0; i < sizeof(buffer); i++)
{
// read one byte at a time
fread(&buffer[i], 1, 1, image);
}
// if block's first 4 bytes match those of a jpg (start of new jpg)
if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xf0) == 0xe0)
{
// close previously opened output file pointer if necessary
if (output != NULL)
{
fclose(output);
}
// create a constant char array for filename
char jpgfile[7];
// name file using ###.jpg format
sprintf(jpgfile, "%03d.jpg", count);
count++;
// open the output file pointer and make sure it's not NULL
if ((output = fopen(jpgfile, "w")) == NULL)
{
printf("Could not write image.\n");
return 1;
}
// write the block containing the photo to the outfile
fwrite(&buffer[0], sizeof(buffer), 1, output);
}
// if outfile has been opened, write the block to the outfile
else if (output != NULL)
{
fwrite(&buffer[0], sizeof(buffer), 1, output);
}
}