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?
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;
FILE *fout;
int c;
fin = fopen ("input.txt", "r");
if (fin != NULL) {
fout = fopen ("output.txt", "w");
if (fout != NULL) {
c = fgetc (fin);
while (c >= 0) {
fputc (c, fout);
c = fgetc (fin);
}
fclose (fout);
} else {
fprintf (stderr, "Cannot write to output.txt");
}
fclose (fin);
} else {
fprintf (stderr, "Cannot read from input.txt");
}
return 0;
}