1

I keep trying to compile this code and it tells me "img" is an undeclared identifier. If I try to declare it, it tells me I'm shadowing a local variable. I'm not sure what the solution is.

I have not been able to run this code, so I'm sure it's riddled with other problems as well. Any help would be appreciated. Thanks!

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

typedef uint8_t  BYTE;

int main(int argc, char *argv[])
{
// ensure proper usage
if (argc != 2)
{
    fprintf(stderr, "Usage: ./recover infile\n");
    return 1;
}

// open input file 
FILE *file = fopen(argv[1], "r");
if (file == NULL)
{
    fprintf(stderr, "Could not open %s.\n", argv[1]);
    return 2;
}

BYTE buffer [512];

// iterate over infiles bytes


// create int to track jpeg file names
int n = 0;

char *filename = 0;

// read 512 bytes
while(!feof(file))
{
    fread(buffer, 1, 512, file);
    if (buffer[0] == 0xff &&
        buffer[1] == 0xd8 &&
        buffer[2] == 0xff &&
        (buffer[3] & 0xf0) == 0xe0)
    {
        // check for first jpeg on memory card
        if (n == 0)
        {
            // open first jpeg file
            sprintf(filename, "%03i.jpg", n);
            FILE* img = fopen(filename, "w");
            fwrite(buffer, 512, 1, img);
            n++;
        }

        // check for all subsequent jpegs on memory cards
        if (n > 0)
        {
            // close open jpeg file
            fclose(img);

            // open next jpeg file
            sprintf(filename, "%03i.jpg", n);
            FILE* img = fopen(filename, "w");
            fwrite(buffer, 512, 1, img);
            n++;
        }
    }
    else if (n > 0)
    {
        fwrite(buffer, 512, 1, img);
    }
} 
// close files
fclose (img);
fclose (file);

// success
return 0;
}

1 Answer 1

2

I estimate the compiler is complainingg about the second fclose (img);. Since image is declared FILE* img = ... within the while loop, you already know you cannot access it outside that loop. Your instinct to declare it outside the loop is correct. You can then use the variable img inside or outside the loop. And you do not have "declare it" again, as with FILE* img = fopen(filename, "w");. You are able to use the variable name without the declaration ie img = fopen(filename, "w");

Hopefully this gets you past the compiler problem. I did a quick scan and Spoiler! char *filename = 0; this is going to give you problems. You know the file name will be 7 long, and since you are creating it as a string with sprintf, it needs +1 for the null byte. Don't forget to allocate it.

You must log in to answer this question.

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