cerror-handlingfopenfwritefclose

C Error: Cannot fopen a file using the same name after fclose it


In this task, I need to create multiple JPEG files. Each time, a file is opened, written, and closed before I open the next file. However, it shows an error when I name the file outptr again although I have closed the file before opening a new one. Can you please tell me what goes wrong here?

Here is the error message:

recover.c:51:23: error: declaration shadows a local variable [-Werror,-Wshadow]
                FILE *outptr = fopen(outfile, "w");
                      ^
recover.c:25:11: note: previous declaration is here
    FILE *outptr = fopen("000.jpg", "w");
          ^
1 error generated.

And here is my original code:

int main(int argc, char *argv[])
{
    // Number of bytes in a block
    const int BLOCK_SIZE = 512;

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


    //File name
    char outfile[7];

    // Create a buffer to copy data
    int16_t buffer[512];
    // Open a random file
    FILE *outptr = fopen("000.jpg", "w");

    int i = -1;


    while (i < 50)
    {
        // While not end of memory card
        while (!(buffer[0] == 0x00 && buffer[1] == 0x00 && buffer[2] == 0x00 && i == 50))
        {
            fread(buffer, sizeof(int16_t) * 512, 1, infile);

            // Check if this block marks the beginning of a new picture
            if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff)
            {
                // Increase file number
                i += 1;

                // Close current output file
                fclose(outptr);

                // Output file name
                sprintf(outfile, "%03d.jpg\n", i);
    
                // Open new output file
                FILE *outptr = fopen(outfile, "w");
                if (outptr == NULL)
                {
                    fclose(infile);
                    fprintf(stderr, "Could not create %s.\n", outfile);
                    return 1;
                }

                // Write buffer to new file
                fwrite(buffer, sizeof(int16_t) * 512, 1, outptr);
            }
            else
            {
                // Write buffer to current file
                fwrite(buffer, sizeof(int16_t) * 512, 1, outptr);
            }

        }
        // Increase i to 50 and break the while loop
        i += 1;
        // Close current output file
        fclose(outptr);
    }
    // Close files
    fclose(infile);
}

Solution

  • You redefined the outptr inside a code block. And in that same codeblock you used the outer scoped variable. That is not legal in C. The fix is this:

    Replace FILE *outptr = fopen(outfile, "w"); in the if block inside the while with this:
    outptr = fopen(outfile, "w");