0

First time on the site, I've been trying to do this pset by myself but as I write this thread, I have already spent easily more than 10 hours only in this code. I have reviewed it thoroughly once and again, and can't tell where my error is.

I suspect that it has to do with fread and fwrite quantity or position of them. Anyway, here's my code, please your help! Thanks in advance.

int main(void)
{
    FILE* inptr = fopen("card.raw", "r");

    if(inptr == NULL)
    {
        printf("File couldn't be opened\n");
        return 1;
    }

    FILE* img = NULL;
    uint8_t buffer[512];
    uint8_t buf[512];
    int counter = 0;
    int Signature = 0;

    char filename[8];

    while(!feof(inptr))
    {        
        Signature = 0;

        if(fread(&buf, 512, 1, inptr) != 1)
            {
            break;
            }         
        fread(&buffer, 512, 1, inptr);

        if((buffer[0] == 0xff) && (buffer[1] == 0xd8) && (buffer[2] == 0xff)  && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
        {            
            if (img != NULL)
            {
                fclose(img);
            }

            sprintf(filename, "%03d.jpg", counter);
            img = fopen(filename, "w");
            Signature = 1;                      
            counter++;
            fwrite(&buffer, 512, 1, img);

            //fread(&buffer, 512, 1, inptr);            
            //printf("%u",buffer[0]);
        }

        if(counter != 0 && Signature == 0)
        { 
            fwrite(&buffer, 512, 1, img);
        }
    }
    if(img != NULL)
    {
        fclose(img);
    }
    fclose(inptr);
    return 0;
}
1

The code does two fread() calls at the top of the while loop. The data from the first fread isn't being processed, it's just being overwritten when the loop comes back around. This means that half the data is being discarded, including, conicidentally, half of the signature blocks.

The inptr file pointer doesn't reset because you're using a different buffer, so the next read is wherever the pointer was positioned after the previous read. Also, the if statement doesn't just check that the amount of data that would be read is correct, it actually executes the read. If you want to do that test, just use that as the read with the buffer used to process the data. No need for a second buffer.

There may be other issues, but this is your main problem. If this answers your question, please click on the check mark to accept. Let's keep up on forum maintenance. ;-)

1
  • Thanks cliff! Did that, adjusted the if statement which identifies the signature for JPEG files, run check50 and all green! I got confused to why it was producing 50 files when it was actually OK the code did that. Gotta remind me to keep self-confidence on my logic next time. Thx! Oct 10 '16 at 23:51

You must log in to answer this question.

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