errno, perror и strerror

Обработка исключений

#include <errno.h>

//a library function reports a failure by its result,
//and leaves the reason in errno (each thread has its own)
FILE *file = fopen("/no/such/file.txt", "r");
bool opened = file != nullptr;
//opened is false
bool notFound = errno == ENOENT;
//notFound is true

//strerror turns the code into text
const char *message = strerror(errno);
//message is "No such file or directory"

//perror prints its prefix and the same text to stderr
perror("fopen");
//stderr: fopen: No such file or directory

//errno is set on failure, but never reset to 0:
//clear it before the call and check it right after
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");