在C/C++中声明和使用FILE*指针的正确方法是什么?

8 c c++ file

在C/C++中声明和使用FILE*指针的正确方法是什么?是应该宣布全球还是本地?有人能展示一个好榜样吗?

pax*_*blo 18

它无论是本地还是全球都无关紧要.文件指针的范围与其使用无关.

一般来说,尽可能避免全局变量是个好主意.

这是一个展示如何从中复制input.txt到的示例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;
}
Run Code Online (Sandbox Code Playgroud)