1

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);
    }
}
  • Thank you for the response. The code for buffer[3] is correct. Zamyla actually provides this in the walkthrough video and it makes sense going through it. buffer(3) & 0xf0 must == oxe0 (1110 0000 in binary) to make that if statement true so it does check for all signatures. – Hoya Coder Mar 3 '17 at 21:17
  • I apologize! You are correct. Shows what you can learn on SE :-) – SuperNovaCoder Mar 3 '17 at 22:11
1

Remove the for loop with the extra freads. You do that in the condition already, so you'd read two blocks, discarding the first.

&buffer[0] is actually same as buffer.

| improve this answer | |
  • Thank you! I was able to get the code to work now. – Hoya Coder Mar 4 '17 at 2:15

You must log in to answer this question.

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