0

I'm wondering if there is a better way of closing file pointers that are in a array other than having a for loop go through the array:

argc -= optind; argv += optind;

FILE *inputfiles[argc - 1];

int i;
for (i = 0; i < argc; i ++)
    inputfiles[i] = fopen(argv[i], "r");

fnctn(inputfiles);

int f;
for (f = 0; f < argc; f++)
    fclose(inputfiles[f]);
user419050
  • 151
  • 5
  • _Side note:_ For your code to work, you have to account for the fact that [upon entry to `main`], `argv[0]` is the program name. The easiest way is: `--argc; ++argv; FILE *inputfiles[argc];` Or, do: `FILE *inputfile[argc - 1]; --argc; ++argv;` – Craig Estey May 17 '21 at 22:28
  • I know, I shift the options with `optind` but forgot to add it here – user419050 May 18 '21 at 22:36

1 Answers1

0

fcloseall exists as a GNU extension. Do know that this also closes stdin, stdout, and stderr.

There is no analogue in standard C.

You can also simply exit your program, and rely on the OS to clean shop. This is generally considered bad practice.


Even though I'm assuming it's mostly mock-code, it should be noted you have a handful of off-by-one errors in your example.

int i;
for (i = 0; i < argc - 1; i ++)
    inputfiles[i] = fopen(argv[i + 1], "r");

int f;
for (f = 0; f < argc - 1; f++)
    fclose(inputfiles[f]);

There's also the case wherein argc is 1, and you will declare a zero-sized array (FILE *inputfiles[1 - 1];), which is invalid in ISO C.

Oka
  • 23,367
  • 6
  • 42
  • 53
  • That's good to know about, and I could use it in this program, but I want to use only standard C so, a `for` loop it is – user419050 May 17 '21 at 22:21