GCC中的简单错误陷阱

时间:2010-07-03 14:43:01

标签: c gcc

使用GCC,我试图在这个程序中添加简单的异常逻辑。理想情况下,简单的“if”可以很好地工作。如果fopen成功则执行x,如果失败则执行z。有一种简单的方法可以做到这一点吗?


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

3 个答案:

答案 0 :(得分:3)

...

If fopen fails, it will return NULL,所以

if (ptr == NULL) {
  do z;
} else {
  do x;
}

答案 1 :(得分:1)

这是一种方法,并报告错误消息:

#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);
  }
}

答案 2 :(得分:1)

如果不符合条件,您可以使用类似的方法检查条件并打印错误:

#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;
}