errno、perror 和 strerror

异常处理

#include <errno.h>

//库函数通过返回值报告失败,
//并把原因留在 errno 中(每个线程各有一个)
FILE *file = fopen("/no/such/file.txt", "r");
bool opened = file != nullptr;
//opened is false
bool notFound = errno == ENOENT;
//notFound is true

//strerror 把错误码转换为文本
const char *message = strerror(errno);
//message is "No such file or directory"

//perror 把前缀和同样的文本输出到 stderr
perror("fopen");
//stderr: fopen: No such file or directory

//失败时会设置 errno,但它从不会被重置为 0:
//调用前先清零,调用后立刻检查
errno = 0;
long big = strtol("99999999999999999999", nullptr, 10);
bool outOfRange = errno == ERANGE;
//outOfRange is true
bool isMax = big == LONG_MAX;
//isMax is true

errno = 0;
long small = strtol("12345", nullptr, 10);
bool failed = errno != 0;
//small is 12345, failed is false

printf("opened is %s\n", opened ? "true" : "false");
printf("notFound is %s\n", notFound ? "true" : "false");
printf("message is %s\n", message);
printf("outOfRange is %s\n", outOfRange ? "true" : "false");
printf("isMax is %s\n", isMax ? "true" : "false");
printf("small is %ld\n", small);
printf("failed is %s\n", failed ? "true" : "false");