什么是声明,并在C / C使用FILE *指针++的正确方法? [英] What is the correct way to declare and use a FILE * pointer in C/C++?

查看:232
本文介绍了什么是声明,并在C / C使用FILE *指针++的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是声明,并在C / C ++使用FILE *指针的正确方法?如果它被声明全局或局部?有人能告诉一个很好的例子?

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.

下面是显示如何从 input.txt的复制到 output.txt的的例子:

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;
}

这篇关于什么是声明,并在C / C使用FILE *指针++的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆