tags:

views:

65

answers:

3

Using GCC, I am trying to add simple exception logic to this program. Ideally, a simple "if" would work well. IF the fopen succeeds then do x, if it fails do z. Is there a simple way to do this?


#include <stdio.h>
main()
{
  FILE *ptr;
  ptr = fopen("c:\\RedyBoot.bat","r");
  fclose(ptr);
  return 0;  
} 
+3  A: 

...

If fopen fails, it will return NULL, so

if (ptr == NULL) {
  do z;
} else {
  do x;
}
KennyTM
Indeed, a very simple way
Tom
+1  A: 

Here is a way to do that and report also the error message:

#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char **argv)
{ 
  FILE *handle;
  errno = 0;                     
  handle = fopen("file.txt", "r");
  if (!handle)
  {
    fprintf (stderr, "Cannot open file %s, error: %s",
             "file.txt", strerror (errno));
    exit (-1);
  }
}
Tarantula
But it would be even better with: `const char fname[] = "file.txt";` and using fname in the two function calls. It's a form of DRY - Don't Repeat Yourself.
Jonathan Leffler
Common.. the objective of the code was to quickly show how to handle and show the error, not a book about C patterns.
Tarantula
+1  A: 

You could use something like this to check the condition and print an error if the condition is not met:

#include <stdlib.h>
#include <stdio.h>

#define CHECK(x) \
    do { \
        if (!(x)) { \
            fprintf(stderr, "%s:%d: ", __func__, __LINE__); \
            perror(#x); \
            exit(-1); \
        } \
    } while (0)

int main()
{
    FILE *file = fopen("my_file.txt", "r");
    CHECK(NULL != file);
    fclose(file);
    return 0;
}
the_void