C++ – the correct way to declare and use a FILE * pointer in C/C++

cfile

What is the correct way to declare and use a FILE * pointer in C/C++? Should it be declared global or local? Can somebody show a good example?

Best Answer

It doesn't matter at all whether it's local or global. The scope of the file pointer has nothing to do with its use.

In general, it's a good idea to avoid global variables as much as possible.

Here's a sample showing how to copy from input.txt to output.txt:

#include <stdio.h>
int main(void) {
    FILE *fin, *fout; int c;

    // Open both files, fail fast if either no good.

    if ((fin = fopen("input.txt", "r")) == NULL) {
        fprintf(stderr, "Cannot read from input.txt");
        return 1;
    }

    if ((fout = fopen("output.txt", "w")) == NULL) {
        fprintf(stderr, "Cannot write to output.txt");
        fclose(fin);
        return 1;
    }

    // Transfer character by character.

    while ((c = fgetc(fin)) >= 0) {
        fputc (c, fout);
    }

    // Close both files and exit.

    fclose(fin);
    fclose(fout);

    return 0;
}