0

Whenever I try to run this code, it returns "could not open file", which means that jptr is assigned a null value. I don't know how to get rid of this, tried so many solutions. It keeps on happening for the above char pointer as well. Here's my code. Any help would be greatly appreciated. Also, If I don't check whether it's null, it returns a segmentation fault.

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

int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        fprintf(stderr, "Usage: Enter recovery image\n");
        return 1;
    }

    // create file name
    char *jpeg = argv[2];

    // create file pointer
    FILE *jptr = fopen(jpeg, "r");
    if (jptr == NULL)
    {

        fprintf(stderr, "could not open file %s.\n", jpeg);
        return 2;
    }

    // create JPEG file
    FILE *img = NULL;

    // create data type
    typedef uint8_t BYTE;
    BYTE buffer[512];


    int count = 0;

    // iterates over each block in the JPEG file.
    while (fread(buffer, 512, 1, jptr))
    {
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] == 0xe1 || buffer[3] == 0xe0))
        {
            char filename[8];
            sprintf(filename, "%03i.jpg", count);
            count++;
            img = fopen(filename, "w");
            if (img == NULL)
            {
                fclose(jptr);
                fclose(img);
                fprintf(stderr, "Could not create file %s.\n", filename);
                return 3;
            }

            fwrite(buffer, 512, 1, img);

        }
    }

    fclose(jptr);
    fclose(img);


    return 0;

}
0

Array indexes in C start with 0. The second element of argv is argv[1]. Whatever argv[2] is and you passed to fopen was the eight bytes (because it's a 64 bit memory address) behind the array.

To expand a bit, array access is a pointer dereferencing. array[index] is same as *(array + index), there is no check for array boundaries. If the array index is far off, you'd likely get an address that is outside of your programme's memory, triggering a "segmentation fault", but those small off-by-one errors are the real evil in the world of C, sometimes exposing protected data, sometimes allowing to inject code.

You must log in to answer this question.

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