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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/589389/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 16:06:49  来源:igfitidea点击:

What is the correct way to declare and use a FILE * pointer in C/C++?

c++cfile

提问by paxdiablo

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?

在 C/C++ 中声明和使用 FILE * 指针的正确方法是什么?它应该被声明为全局还是本地?有人可以举一个很好的例子吗?

回答by paxdiablo

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.txtto output.txt:

这是一个示例,展示了如何从input.txtto复制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;
}

回答by Crashworks

It's just an ordinary pointer like any other.

它只是一个普通的指针,就像任何其他指针一样。

FILE *CreateLogFile() 
{
    return fopen("logfile.txt","w"); // allocates a FILE object and returns a pointer to it
}

void UsefulFunction()
{
   FILE *pLog = CreateLogFile(); // it's safe to return a pointer from a func
   int resultsOfWork = DoSomeWork();
   fprintf( pLog, "Work did %d\n", resultsOfWork );  // you can pass it to other functions
   fclose( pLog ); // just be sure to clean it up when you are done with fclose()
   pLog = NULL;    // and it's a good idea to overwrite the pointer afterwards
                   // so it's obvious you deleted what it points to
}

回答by Chris Lutz

int main(void)
{
  char c;
  FILE *read;
  read = fopen("myfile", "r"); // opens "myfile" for reading
  if(read == NULL)
  {
    perror("Error: could not open \"myfile\" for reading.\n");
    exit(1);
  }
  c = fgetc(read);
  fclose(read);
  printf("The first character of myfile is %c.\n", c);
  return 0;
}

You're perfectly allowed to declare global filehandles if you like, just like any other variable, but it may not be recommended.

如果愿意,您完全可以声明全局文件句柄,就像任何其他变量一样,但可能不建议这样做。

This is the C way. C++ can use this, but I think there's a more C++ friendly way of doing it. As a note, I hate it when questions are marked C/C++, because C and C++ are notthe same language and do notwork the same. C++ has a lot of different ways to do things that C doesn't have, and they may be easier for you to do in the context of C++ but are not valid C. So while this will work for either language, it's not what you want if you predominantly use C++.

这是C方式。C++ 可以使用它,但我认为有一种更 C++ 友好的方式来做到这一点。作为一个说明,我恨它,当问题被标记为C / C ++,因为C和C ++是不是同一种语言,也没有工作一样。C++ 有很多不同的方法来做 C 没有的事情,在 C++ 的上下文中它们可能更容易让你做,但不是有效的 C。所以虽然这对任何一种语言都有效,但这不是你想要的如果您主要使用 C++,则需要。

EDIT: Added some error checking. Always use error checking in your code.

编辑:添加了一些错误检查。始终在代码中使用错误检查。

回答by Andrew Barrett

Here is the first hit on google for "file io in c"

这是谷歌上第一次点击“c 中的文件 io”

http://www.cs.bu.edu/teaching/c/file-io/intro/

http://www.cs.bu.edu/teaching/c/file-io/intro/

Here is the third hit from gamedev with more of a C++ slant

这是 gamedev 的第三个热门,更多的是 C++ 倾向

http://www.gamedev.net/reference/articles/article1127.asp

http://www.gamedev.net/reference/articles/article1127.asp

You declare the pointer in the scope that you need it.

您在需要它的范围内声明指针。

回答by Tim Post

First, keep in mind that a file pointer (and the associated allocated structure) is based on the lower level open() read() write() calls. The associated file descriptor (obtained by fileno(file_pointer) is the least interesting thing, but something you might want to watch your scope with.

首先,请记住文件指针(以及相关的分配结构)基于较低级别的 open() read() write() 调用。关联的文件描述符(由 fileno(file_pointer) 获得)是最不有趣的东西,但你可能想用它来观察你的作用域。

If your going to declare a file pointer as global in a module, its usually a very good idea to keep it static (contained within that module / object file). Sometimes this is a little easier than storing it in a structure that is passed from function to function if you need to write something in a hurry.

如果要在模块中将文件指针声明为全局文件指针,通常最好将其保持为静态(包含在该模块/目标文件中)。有时,如果您需要匆忙写一些东西,这比将它存储在从一个函数传递到另一个函数的结构中更容易一些。

For instance, (bad)

例如,(坏)

#include <stdio.h>
#include ...

#define MY_LOG_FILE "file.txt"

FILE *logfile

Better done as:

最好这样做:

#include <stdio.h>

#define MY_LOG_FILE "file.txt"

static FILE *logfile;

int main(void)
{

UNLESS, you need several modules to have access to that pointer, in which case you're better off putting it in a structure that can be passed around.

除非,您需要多个模块才能访问该指针,在这种情况下,最好将其放在可以传递的结构中。

If its needed only in one module, consider declaring it in main() and letting other functions accept a file pointer as an argument. So, unless your functions within the module have so many arguments that another would be unbearable .. there's (usually) no reason to declare a file pointer globally.

如果仅在一个模块中需要它,请考虑在 main() 中声明它并让其他函数接受文件指针作为参数。所以,除非你在模块中的函数有太多的参数,另一个是无法忍受的......(通常)没有理由全局声明文件指针。

Some logging libraries do it, which I don't care for ... especially when dealing with re-entrant functions. Nevermind C's monolithic namespace :)

一些日志库会这样做,我不关心……尤其是在处理可重入函数时。没关系 C 的整体命名空间 :)