0

Going crazy here, help much appreciated:). I think I am messing something up with the scope. Here is my analysis for what it's worth: I am declaring img within the if & else conditions. Because of this I can not use it in the final if statement where I must write to the img file. To fix this I previously tried to declare img outside of the do while loop. However that also did not work, because it gave the error message "shadowing local variables". Really don't know how to solve this..

Thanks! CB

/**
 * recover.c
 *
 * Computer Science 50
 * Problem Set 4
 *
 * Recovers JPEGs from a forensic image.
 */

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

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

    // initialize jpeg counter at 000
    int jpg_no = 0;

    // initialize buffer
    uint8_t buffer[512];

    // repeat until end of file
    do
    {    
        // read 512 byes into buffer
        fread(&buffer, 512, 1, inptr);

        // is it a new jpeg?
        if(buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff
        && (buffer[3] == 0xe0 || buffer[3] == 0xe1))
        {
            // if 1st file, then open 1st file
            if(jpg_no == 0)
            {
                char* title;
                sprintf(title, "%03d.jpg", jpg_no);
                FILE* img = fopen(title, "a");
            }

            // else close previous file and open new one
            else
            {
                fclose(img);
                char* title;
                sprintf(title, "%03d.jpg", jpg_no);
                FILE* img = fopen(title, "a");
            }

            // update the jpeg counter
            jpg_no++;
        }

        // already found a jpeg?
        if(jpg_no > 0)
        {
            // write to open jpeg
            fwrite(&buffer, 512, 1, img);
        }
    }

    // while sizeof buffer = 512
    while(fread(&buffer, 512, 1, inptr) == 1);

    // close remaining files
    fclose(img);
    fclose(inptr);

    // the end
    return 0;
}
0

If you're getting that message, it means that you are re-declaring img somewhere. You are on the right track though. Declare FILE* img = NULL; at the top of the program and make sure that you don't have FILE* later on when you use img.

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

1
  • Thanks, that worked. I fixed that + some other stuff that lead to a segmentation fault. It now compiles, but produces 25 scrambled jpegs :(
    – CB Nuji
    May 16 '16 at 12:04

You must log in to answer this question.

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