0

I've reviewed my code and I think it should work, but only the first 512 bytes are being written, not sure why.

#include<stdio.h>
#include<stdlib.h>

#include<stdint.h>

typedef uint8_t BYTE;


int main (int argc, char* argv[])
{
    // open card file
    FILE* inptr = fopen("card.raw", "r");
    if (inptr == NULL)
    {
        printf("Could not open card.raw.\n");
        return 1;
    }

    FILE* outptr = NULL;

    int picnum = 0;
    char* photofile = malloc(sizeof(char)*7);

    // read into memory block and search jpg header
    while (0 < 1)
    {        
        BYTE memblock[512];

        if (fread(&memblock, (sizeof(BYTE) * 512), 1, inptr) == 1)
        {
            // fnd jpg header
            if (memblock[0] == 0xff && memblock[1] == 0xd8 && memblock[2] == 0xff && (memblock[3] == 0xe0 || memblock[3] == 0xe1))
            {
                // close previous photo file if open
                if(outptr != NULL)
                fclose(outptr);

                // create new photo file name
                if(picnum >= 0 && picnum <= 9)
                {
                    sprintf(photofile, "00%d.jpg", picnum);
                }
                else if(picnum >= 10 && picnum <= 99)
                {
                    sprintf(photofile, "0%d.jpg", picnum);
                }
                else if(picnum >= 100 && picnum <= 999)
                {
                    sprintf(photofile, "%d.jpg", picnum);
                }

                // create new photofile
                FILE* outptr = fopen(photofile, "a");
                if (outptr == NULL)
                {
                    fclose(inptr);
                    printf("Error opening new photofile\n");
                    return 1;
                }

                // write first block
                fwrite(&memblock, (sizeof(BYTE) * 512), 1, outptr);

                picnum++;
            }
            else if (outptr != NULL)
            {
                fwrite(&memblock, (sizeof(BYTE) * 512), 1, outptr);
            }

        }
        else
        {
            break;
        }
    }
}
0

You are redeclaring outptr with FILE* outptr = fopen(photofile, "a"); and creating a shadow variable that is only in scope inside of the if statement. Once you exit the if statement, the shadow copy of outptr, which actually points at the file, goes out of scope and disappears. The original outptr still exists and points at NULL, so the code acts accordingly and never writes the buffer data out. The result is that only signature blocks are being written out.

There may be more problems with your code, but this is why you are only writing out 512 bytes per file.

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

You must log in to answer this question.

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