Taggagii
Taggagii

Reputation: 81

If you create a function which opens files, do those files automatically "fclose()" after the function has returned?

To further explain the concept, I have included an example function that opens files:

int compare_files(const char *filenameone, const char* filenametwo)
{
    FILE *mainfile = fopen(filenameone, "r");
    FILE *checkerfile = fopen(filenametwo, "r");
    int value = 1;
    if (!mainfile || !checkerfile)
    {
        value = -1;
        goto END;
    }
    int letter, letter2;
    while ((letter = fgetc(mainfile)) != EOF && (letter2 = fgetc(checkerfile)) != EOF)
        if (letter != letter2)
        {
            value = 0;
            break;
        }
END:
    fclose(mainfile);
    fclose(checkerfile);
    return value;
}

In the above example, would I need to call fclose() for mainfile and checkerfile? Or would those files be closed once the function completes?

Upvotes: 1

Views: 128

Answers (1)

klutt
klutt

Reputation: 31389

The general answer to "Does X happen automatically in C?" is: No

And so is it in this case. Usually, open files are closed when you reach the end of the main function or invoke the exit() function. Same thing with dynamically allocated memory. But if the program exits abnormally, for instance because division by zero or segmentation fault, this could cause trouble. However, there are environments where this does not happen. It's quite common in embedded systems.

So close your files when you're done with them. And free all allocated memory. It's a good habit.

I would write your function like this:

int compare_files(const char *filenameone, const char* filenametwo)
{
    int ret = -1;
    FILE *mainfile = fopen(filenameone, "r");
    if(!mainfile) goto EXIT1;
    FILE *checkerfile = fopen(filenametwo, "r");
    if(!checkerfile) goto EXIT2;

    ret = 1;
    // Not related to your question, but these should be int since
    // a char cannot hold the value EOF
    int letter, letter2;
    while ((letter = fgetc(mainfile)) != EOF && (letter2 = fgetc(checkerfile)) != EOF) {
        if (letter != letter2) {
            ret = 0;
            break;
        }
    }

    fclose(checkerfile);
EXIT2:
    fclose(mainfile);
EXIT1:
    return ret;
}

Upvotes: 3

Related Questions