0

I feel like I am so close, but I get a segmentation error, it expects 0 and returns 2 (my usage statement). Can someone explain this to me? I'm really confused on why it is returning this statement. Thank you.

int main(int argc, char* argv[]) { if (argc != 2) { //if input from user is incorrect as specification suggested fprintf(stderr, "Usage: ./recover image\n"); return 1; }

    //remember file name
    char *infile = argv[1];
    FILE *inptr = fopen(infile, "r");
    //checks return value to ensure you dont get NULL value
    if (inptr == NULL)
    {
        //if file cannot open
        fprintf(stderr, "Cannot be opened for reading\n");
        return 2;
    }


    //establish values, creates a 512 byte buffer
    BYTE buffer[BLOCK];
    //counter to keep track of files starting from 000
    int count = 0;
    //if jpeg was found yet or not it will mean false
    int peg = 0;
    //file name for opening a new JPEG and current location
    FILE *outptr = NULL;
    char name[8];

    //repeat and read until end of file
    while (fread(&buffer, BLOCK, 1, inptr) == 1)
    {

        //find beginning of JPEG
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
        {

            //if first JPEG file is found close previous file 
            if (peg == 1)
            {
                fclose(outptr);
            }
            //else new JPEG found, close current file, start new image
            else
            {
                //create a file name to write new JPEG
                peg = 1;

            }

            sprintf(name, "%03i.jpg", count); //example uses 2
            inptr = fopen(name, "w");
            count++;

        }

        //write 512 bytes to file
        if (peg == 1)
        {
            fwrite(&buffer, BLOCK, 1, outptr);

        }

    }

//close any open files
fclose(outptr);
fclose(inptr);

return 0;

} enter image description here

0

Looks like a typo here:

 sprintf(name, "%03i.jpg", count); //example uses 2
 inptr = fopen(name, "w"); // <-----------TYPO?
 count++;

Since inptr is the input file.

It always a good idea to run your programs and review/verify the outputs before checking with check50.

1
  • Thank you so much! It works perfectly now. I can't believe it was a typo that made me stuck for two days! Thank you again! – see90 Feb 25 '17 at 22:21

You must log in to answer this question.

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