0

I'm having trouble figuring out how to print extra 512bytes, if the first jpg is longer than that, like how to loop UNTIL it hits the next 4 header indicators. In this code example I've tried with a do while loop, but it gives me a segmentation fault.

When I check the buffer[0],[1],[2] etc in this while loop, does it check the same values that my if condition checked? Or will it have updated the values in buffer[0],[1],[2],[3] ?

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

int main(int argc, char* argv[])
{
    if (argc != 2)
    {
        fprintf(stderr,"needs 2 arguements\n");
        return 1;

    }


    char *infile = argv[1];

    // open memory card file to read
    FILE *inptr = fopen(infile, "r");

    if (inptr == NULL)
    {
        fprintf(stderr,"Could not open\n");
        return 2;
    }
    int tracker = 0;
    //temporary storage 
        int buffer[511];

    // iterate over the card file, checking for eof
    while(fread(&buffer,512,1,inptr) == 1)
    {
        // variable to store title name of file
        char filename[8];

        // Creating a new jpg file
        sprintf(filename, "%3i.jpg",tracker);
        FILE *img = fopen(filename, "w");
        img = NULL;



        fread(&buffer, 512, 1, inptr);

        // check for jpg header indicator
        if(buffer[0] == 0xff &&
            buffer[1] == 0xd8 &&
            buffer[2] == 0xff &&
            (buffer[3] & 0xf0) == 0xe0)
        {

            // IF file is opened
            if (img != NULL)
            {
                fclose(img);
            } else {

                do { 
                fwrite(&buffer, 512,1,img);    
                } while(buffer[0] != 0xff &&
                    buffer[1] != 0xd8 &&
                    buffer[2] != 0xff &&
                    (buffer[3] & 0xf0) != 0xe0);
            }


        } 
        fwrite(&buffer, 512,1,img);

        //update xxx.jpg tracker var
        tracker++;
        fclose(img);


    }
}
0

Try to use flags i.e. declare integer variables and set them to zero initially. Then when you find any JPEG, set flag1 and flag2 to one and open and write to file. Then, set flag1 back to zero and check if there is a new JPEG, if there is then set flag1 to one and flag2 to one. In that case, close the previous file if flag2 is one and open a new file and write to it. In case you don't find a JPEG, then flag1 will be zero and flag2 is one as your previous JPEG is continued, so write to the file which is already open.

Try to understand this logic and implement it in the while loop.

You must log in to answer this question.

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