create array of pointers to files

那年仲夏 提交于 2020-04-08 06:40:21

问题


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

From argv, I would like to create the array of files/file pointers. 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");

回答1:


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

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

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

// operations...

free(inputFiles);



回答2:


#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 :)



来源:https://stackoverflow.com/questions/2242901/create-array-of-pointers-to-files

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!