#include <errno.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
static int safe_divide(int dividend, int divisor, int *quotient) {
if (divisor == 0) {
return EXIT_FAILURE;
}
*quotient = dividend / divisor;
return EXIT_SUCCESS;
}
int main(void) {
/* Case 1: fopen on missing file sets errno = ENOENT and strerror describes it */
errno = 0;
FILE *pf = fopen("/tmp/definitely_nonexistent_mbsky_file_404.bin", "rb");
int errnum = errno;
const char *errmsg = strerror(errnum);
int c1_pass = (pf == NULL && errnum == ENOENT && errmsg != NULL && strlen(errmsg) > 0);
/* Case 2: guarded division rejects zero divisor without crash */
int q_bad = -999;
int st_bad = safe_divide(20, 0, &q_bad);
int c2_pass = (st_bad == EXIT_FAILURE && st_bad != 0 && q_bad == -999);
/* Case 3: valid division returns EXIT_SUCCESS (0) and quotient 4 */
int q_ok = 0;
int st_ok = safe_divide(20, 5, &q_ok);
int c3_pass = (st_ok == EXIT_SUCCESS && EXIT_SUCCESS == 0 && q_ok == 4);
/* Case 4: resetting errno before math domain error (EDOM) */
errno = 0;
volatile double neg = -1.0;
double r = sqrt(neg);
int math_err = errno;
int is_nan_res = isnan(r) != 0;
int c4_pass = (is_nan_res && (math_err == EDOM || math_err == 0));
printf("{\n");
printf(" \"runtime\": \"GCC C11 (mstorsjo/llvm-mingw:20260616)\",\n");
printf(" \"cases\": [\n");
printf(" {\"name\": \"errno_and_strerror\", \"expected\": {\"null_fp\": true, \"enoent\": true, \"has_msg\": true}, \"actual\": {\"null_fp\": %s, \"enoent\": %s, \"has_msg\": %s}, \"passed\": %s},\n",
(pf == NULL) ? "true" : "false", (errnum == ENOENT) ? "true" : "false", (errmsg != NULL && strlen(errmsg) > 0) ? "true" : "false", c1_pass ? "true" : "false");
printf(" {\"name\": \"divide_by_zero_guard\", \"expected\": {\"failed\": true, \"untouched\": -999}, \"actual\": {\"failed\": %s, \"untouched\": %d}, \"passed\": %s},\n",
(st_bad == EXIT_FAILURE) ? "true" : "false", q_bad, c2_pass ? "true" : "false");
printf(" {\"name\": \"exit_success_and_quotient\", \"expected\": [0, 4], \"actual\": [%d, %d], \"passed\": %s},\n",
st_ok, q_ok, c3_pass ? "true" : "false");
printf(" {\"name\": \"errno_reset_and_math_domain\", \"expected\": true, \"actual\": %s, \"passed\": %s}\n",
is_nan_res ? "true" : "false", c4_pass ? "true" : "false");
printf(" ]\n");
printf("}\n");
return 0;
}
本例需在 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程
运行环境:本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。
入口文件:projects/c-error-handling-lab/explore-error-handling.c
本地运行步骤快速上手
- 点击上方“保存源码”保存为
explore-error-handling.c,或下载右侧课程工程包。 - 确认本地已准备 本地离线 Docker 容器(mstorsjo/llvm-mingw:20260616,GCC C11 linux/amd64,--network none)。。
- 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载
课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a3219.zip
课程关联工程包(登记关联63章) · 含当前章节或实例 · mbskycom202612a3210.zip