C语言 创建指向文件的指针数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2242901/
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-09-02 04:26:57  来源:igfitidea点击:

create array of pointers to files

cfileioargv

提问by Hristo

How would I go about making an array of file pointers in C?
I would like to create an array of file pointers to the arguments of main... like a1.txt, a2.txt, etc... So I would run ./prog arg1.txt arg2.txt arg3.txtto have the program use these files.
Then the argument for main is char **argv

我将如何在 C 中制作文件指针数组?
我想创建一个指向 main 参数的文件指针数组……比如 a1.txt、a2.txt 等……所以我会运行./prog arg1.txt arg2.txt arg3.txt让程序使用这些文件。
那么 main 的参数是char **argv

From argv, I would like to create the array of files/file pointers. This is what I have so far.

从 argv,我想创建文件/文件指针数组。这是我到目前为止。

FILE *inputFiles[argc - 1];
int i;
for (i = 1; i < argc; i++)
    inputFiles[i] = fopen(argv[i], "r");

回答by kennytm

The code is fine, but remember to compile in C99.

代码没问题,但记得用C99编译。

If you don't use C99, you need to create the array on heap, like:

如果不使用 C99,则需要在堆上创建数组,例如:

FILE** inputFiles = malloc(sizeof(FILE*) * (argc-1));

// operations...

free(inputFiles);

回答by Arthur Kalliokoski

#include <stdio.h>`

int main(int argc, char **argv)
{
FILE *inputFiles[argc - 1];
int i;
for (i = 1; i < argc; i++)
{
    printf("%s\n",argv[i]);
    inputFiles[i] = fopen(argv[i], "r");
    printf("%p\n",inputFiles[i]);
}
  return 0;
}

It prints different pointers for each file pointer along with the names. Allowing OS to close files properly :)

它为每个文件指针以及名称打印不同的指针。允许操作系统正确关闭文件:)