简体   繁体   English

创建指向文件的指针数组

[英]create array of pointers to files

How would I go about making an array of file pointers in C? 我如何在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.txt to have the program use these files. 我想创建一个指向main的参数的文件指针数组...如a1.txt,a2.txt等...所以我会运行./prog arg1.txt arg2.txt arg3.txt来获取程序使用这些文件。
Then the argument for main is char **argv 然后main的参数是char **argv

From argv, I would like to create the array of files/file pointers. 从argv,我想创建文件/文件指针数组。 This is what I have so far. 这就是我到目前为止所拥有的。

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

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);
#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 :) 允许操作系统正确关闭文件:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM