Simple Error Trap in GCC
Using GCC, I am trying to add simple exception logic to this program. Ideally, a simple "if" would work 开发者_如何学Pythonwell. 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;
}
...
If fopen
fails, it will return NULL, so
if (ptr == NULL) {
do z;
} else {
do x;
}
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);
}
}
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;
}
精彩评论