0

My code for pset3 works and recovers all the images as it is supposed to however I realised that when I call fopen the first value in my buffer array becomes 0 I fixed this by changing the value back to 0xff right after I call fopen but I have no idea why fopen is doing this, I hope that someone could help me understand why exactly this is happening.

while (fread(buffer, 512, 1, inptr) != 0)
{
    if ((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff) && ((buffer[3] & 0xf0) == 0xe0))
    {
        if (i > 0)
        {
            fclose(img);
        }
        sprintf(filename, "%03i.jpg", i);
        img = fopen(filename, "w");
        i++;
        buffer[0] = 0xff;
    }
    fwrite(buffer, 512, 1, img);
}

(I didnt post all of the code since I am not sure if that goes against the academic honesty policy but I think this should be enough)

The if statement only triggers when buffer[0] == 0xff but somehow if I don't include buffer[0] = 0xff; after the call to fopen the value changes to 0 I know this from checking the hexadecimal for the files being made. Am I just missing something or is fopen really changing the values?

1

I'll bet money on this one. What's the declaration for filename? Is it less than 8 chars? I bet it's 7 chars long and you forgot about the end of string marker.

This is a very common error in this pset. When the filename string is written to filename, the entire string is written out, including the EOS marker, no matter what the length of filename may be. If 7 chars were allocated, the EOS marker overwrites the next byte in physical memory, which often is the first byte of the buffer. Thus, the first byte becomes 0x00.

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

1
  • That was exactly it I completely forgot about the string ending and only had 7 characters for my filename just as you said thank you very much I really appreciate the help. – Murtada Alzubaidi Apr 19 '19 at 0:18

You must log in to answer this question.

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