0
    // img file pointer
    FILE* img = NULL;
    char* file_name = NULL;
    int file_count = 0;
    int bytes_written = 512;

    // repeat until end of memory card
    while (bytes_written == 512) // Read 512 bytes into a buffer
    {
        // buffer
        unsigned char bytes[512];
        // read into buffer
        fread(bytes, 512, 1, raw_file);

        // if start of new JPEG
        if (bytes[0] == 0xff && bytes[1] == 0xd8 && bytes[2] == 0xff && (bytes[3] & 0xf0) == 0xe0)
        {
            // if first JPEG
            if (file_count == 0) // write file 000
            {
                // make file name
                sprintf(file_name, "%03i.jpg", file_count);

                // open a new file of file_name
                img = fopen (file_name, "w");

                // write to file
                bytes_written = fwrite (bytes, 512, 1, img);

                // increase file_count
                file_count++;
            }

            // else if not first JPEG (close previous file)
            else
            {
                // close previous file
                fclose (img);

                // open new file
                sprintf(file_name, "%03i.jpg", file_count);

                // open a new file of file_name
                img = fopen (file_name, "w");

                // write to file
                bytes_written = fwrite (bytes, 512, 1, img);

                // increase file_count
                file_count++;
            }
        }
        else
        {
            // if already found JPEG and been writing to it
            if (img != NULL)
            {
                // keep writing to it
                bytes_written = fwrite (bytes, 512, 1, img);
            }
        }
    }
    // close any remaning files
    fclose (img);

Ok so i am trying to store the FILE* img (pointer) as a variable outside of the loop.

I set img initially to null, but once the loop finds a file in the bytes array and it tries to write to file i get a segmentation fault.

I think it may be due to my storing the img as a variable but I'm not sure.

Any help is greatly appreciated even if your a beginner! because sometimes i make simple mistakes.

0

Close, but no. The var file_name is a pointer that is set to null. No space is ever allocated to it using malloc. When the sprintf command tries to write the filename into it, it generates a seg fault.

There are two fixes here. You can malloc space to filename, or you can create a non-pointer string (char array) of sufficient length to hold the file names.

I recommend the latter. A char array or string is a reusable var that doesn't require the overhead of manually allocating memory and freeing it later.

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 .