0

I'm working on recover and I think I'm nearly there but I can't resolve an issue with file pointers. When I'm compiling I'm getting two errors both say error: use of undeclared identifier 'ptr'.

I think it's something to do with the scope but I'm struggling to find exactly what so any help would be appreciated!

    // Check first four bytes to detemine if it's the start of a jpeg
        if (jpgchk[0] == 0xff && jpgchk[1] == 0xd8 && jpgchk[2] == 0xff && (jpgchk[3] & 0xf0) == 0xe0)
        {   
            if (filecount == 0) // check if it's the first file
            {
                sprintf(filename, "%03i.jpg", filecount);   // set filename
                FILE *ptr = fopen(filename, "w");           // open new file
                if (!ptr)
                {
                    return 1;
                }
                fwrite(jpgchk, 1, 512, ptr);        // write first 512bytes
            }
            else // if not the first file
            {
                fclose(ptr);                                // close previous file
                filecount++;                                // increment filecount
                sprintf(filename, "%03i.jpg", filecount);   // rename filename
                FILE *ptr = fopen(filename, "w");           // open new file
                fwrite(jpgchk, 1, 512, ptr);        // write first 512bytes
            }
        }
        else // if not start of a jpeg
        {
            fwrite(jpgchk, 1, 512, ptr);            // write data to file
        }

The errors appear on the fclose() and the fwrite() in the outside else statement

2

Yup, it's all about scope.

Since the file pointers are being declared inside the IF code blocks, they cease to exist when processing leaves those code blocks. Remember, a variable only exists within the closest pair of curly braces that surround it.

To fix this, declare the pointers for the input and output files at the top of the program and initialize them to NULL. They will be in scope for the entirety of main(). You can open and close them as many times as needed, they will still be there for you to reuse. You'll reassign them to actual files when they're needed later. Problem solved!

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

3
  • Thank you. That's fixed the compiler error. Now just need to work on the segmentation fault I get when I try and run it!!
    – Wh0am3ye
    Aug 3 '20 at 17:52
  • Glad to hear it. Seg fault would be for a new question, ;-)
    – Cliff B
    Aug 3 '20 at 19:52
  • Thanks this saved mmy life Sep 25 '20 at 16:46

You must log in to answer this question.

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