[英]Simple Error Trap in GCC
使用GCC,我試圖向該程序添加簡單的異常邏輯。 理想情況下,簡單的“ if”將很好地工作。 如果fopen
成功,則執行x,如果失敗,則執行z。 有沒有簡單的方法可以做到這一點?
#include <stdio.h>
main()
{
FILE *ptr;
ptr = fopen("c:\\RedyBoot.bat","r");
fclose(ptr);
return 0;
}
這是執行此操作並報告錯誤消息的一種方法:
#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);
}
}
您可以使用類似這樣的方法來檢查條件並在不滿足條件時顯示錯誤:
#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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.