3

I was wondering what would be the best and/or fastest way to NULL check multiple file pointers and rule out the 'bad' (NULL) ones? Can this be achieved via the switch statement?

My 'normal/basic' approach would be:

FILE *fp1, *fp2, *fp3;

fp1 = fopen(foo, bar);
/* etc.. */

if (!fp1) 
    /* do something */
    return 1;
if (!fp2) 
    return 2;

... 

.. but this approach just seems too long, especially if there's too many pointers to check. Is there a trick to do this more conveniently?

In other words (or code), something like this:

if (!fp1 || !fp2 || !fp3) {
    /* one of the pointers is NULL, let's *somehow* check which one it is */
} else {
    /* everything OK */
} 

I'm a beginner and I was thinking of using the switch statement. To be more specific, I was thinking of (again) somehow comparing the file pointers to NULL, but I can't figure out how I'd write such code, since the expression used in switch statement must be an integer, but on the other hand, doesn't NULL equal 0?

I apologize, since this seems to be a trivial question, but I couldn't find anything on null checking multiple pointers like this.

Thanks in advance!

annoyingnoob
  • 63
  • 1
  • 5
  • 9
    When you find yourself creating multiple objects named `thing_N`, where `N` is a number, that's a real strong hint you want an *array* - `FILE *fp[3]`. That way you can use a loop to do the check - `for ( int i = 0; i < 3; i++ ) { if ( !fp[i] ) { /* handle file error */ } }`. – John Bode Dec 20 '19 at 17:36
  • @John Bode Oh wow, that is really, really convenient! Thank you so much for the tip! – annoyingnoob Dec 20 '19 at 17:44

1 Answers1

1

There isn't a best way to do this. The compiler with the right optimization is the only solution. Switch or if are the same things when the code is compiled.

Only a tips if the number of file to open is big, is a good things for a readable code to use an array and a cycle to loop on it. But if your goal is the performance the cycle is not the best way to do that, expecially if the number of element to check are small.

Zig Razor
  • 3,381
  • 2
  • 15
  • 35