0

I've encoutered a weird bug in recover.c the following is my code and an error occurs at the last part.

recover.c:65:5: error: type specifier missing, defaults to 'int' [-Werror,-Wimplicit-int] fclose(outfile);

I searched for this error and it seems not even related with "fclose" function. Can anyone help? Many thanks!

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

typedef uint8_t BYTE;
int BLOCK_SIZE = 512;

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

    // Open input file
    FILE *infile = fopen(argv[1], "r");
    if (infile == NULL)
    {
        printf("Could not open %s.\n", argv[1]);
        return 2;
    }
    //allocate memory for file name and for buffer
    char *filename = malloc(8 * sizeof(char));
    BYTE *buffer = malloc(BLOCK_SIZE * sizeof(BYTE));
    //sprintf(filename,"000.jpg");
    int k = 0;
    FILE *outfile;

    while (fread(buffer, 1, BLOCK_SIZE, infile) == BLOCK_SIZE)
    {
        //find the signature
        if (buffer[0] == 0xff && buffer[1] == 0xd8 && buffer[2] == 0xff && (buffer[3] & 0xe0) == 0xe0)
        {
            if (k == 0)
            {
                //create and write the first image
                k = k + 1;
                sprintf(filename, "%03i.jpg", k-1);
                outfile = fopen(filename,"w");
                fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
            }
            else
            {
                //create and write the following images
                fclose(outfile);
                k = k + 1;
                sprintf(filename, "%03i.jpg", k-1);
                outfile = fopen(filename,"w");
                fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
            }
        }
        else
        {
            if (k != 0)
            {
                fwrite(&buffer, sizeof(BYTE), BLOCK_SIZE, outfile);
            }
        }
    }
}

    // Close outfile
    fclose(outfile);
    fclose(infile);
    free(filename);
    free(buffer);
    return 0;
}

1 Answer 1

0

You are right, it is not (exactly) related to fclose. When that happens (a syntax error on an arguably correct line), you should suspect the line before. That is a }, so the next quest is to find the "unbalanced" {}. VS Code web shows the last '}' in red, which indicates it is unmatched. The preceding } (before the fclose line) closes the main loop. Remove (or comment) it.

1
  • thanks! I found the extra "}" in my code.
    – Eva Chen
    Commented Dec 25, 2022 at 14:13

You must log in to answer this question.

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