create array of pointers to files
Asked Answered
C

2

7

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");
Chickenlivered answered 11/2, 2010 at 7:34 Comment(1)
I can't find anything wrong with it. What's the problem?Misjoinder
D
7

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);
Dunbar answered 11/2, 2010 at 7:38 Comment(3)
Thanks. So just for testing sake, how would I print the names of the files that the array pointers point to?Chickenlivered
@Chickenlivered - there is no way to recover the name of the file from the FILE*. But since you have the argv array, the file name of inputFiles[n] can be found at argv[n].Glidewell
yes, i have the names of the files stored in another array, i was just wondering if I can do it the other way. I'm new to C, this is my 4th week :)Chickenlivered
M
1
#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 :)

Misjoinder answered 11/2, 2010 at 7:52 Comment(1)
Thanks. That makes a lot of sense!Chickenlivered

© 2022 - 2024 — McMap. All rights reserved.