Last active
August 3, 2019 16:38
-
-
Save mizdra/2ef896186de5bfc071f6820870615336 to your computer and use it in GitHub Desktop.
Cでまともなエラーメッセージを出すマクロ (based on http://doi-t.hatenablog.com/entry/2013/12/10/094837)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <errno.h> | |
#include <stdarg.h> | |
#include <stdio.h> | |
#include <string.h> | |
#define PANIC(fmt, ...) \ | |
{ \ | |
err_msg(__FILE__, __FUNCTION__, __LINE__, "panic", fmt, ##__VA_ARGS__); \ | |
exit(EXIT_FAILURE); \ | |
} | |
#define ERROR(fmt, ...) \ | |
err_msg(__FILE__, __FUNCTION__, __LINE__, "error", fmt, ##__VA_ARGS__) | |
#define WARNING(fmt, ...) \ | |
err_msg(__FILE__, __FUNCTION__, __LINE__, "warning", fmt, ##__VA_ARGS__) | |
#define RED "\033[0;31m" | |
#define BOLD "\033[1m" | |
#define RESET_COLOR "\033[0m" | |
void err_msg(const char *file, const char *function, int line, const char *type, | |
const char *fmt, ...) { | |
// print error message | |
fprintf(stderr, RED); | |
fprintf(stderr, "%s: ", type); | |
va_list va; | |
va_start(va, fmt); | |
vfprintf(stderr, fmt, va); | |
va_end(va); | |
fprintf(stderr, RESET_COLOR); | |
fputc('\n', stderr); | |
// print error source | |
fprintf(stderr, BOLD); | |
fprintf(stderr, " --> `%s` (%s:%d)", function, file, line); | |
fprintf(stderr, RESET_COLOR); | |
fputc('\n', stderr); | |
// print errno | |
if (errno != 0) { | |
fprintf(stderr, " = errno: %s(%d)", strerror(errno), | |
errno); // print errno | |
fputc('\n', stderr); // new line | |
errno = 0; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <fcntl.h> | |
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include "error.h" | |
int print_file_header(char *path) { | |
int fd = open(path, O_RDONLY, 0644); | |
if (fd == -1) { | |
ERROR("fail to open file"); | |
return -1; | |
} | |
char buf[10]; | |
if (read(fd, buf, 10) == -1) { | |
ERROR("fail to read file"); | |
return -1; | |
} | |
printf("%s\n", buf); | |
return 0; | |
} | |
int main() { | |
if (print_file_header("nonexistent_file.txt") == -1) { | |
PANIC("failt to `print_file_header`"); | |
} | |
return EXIT_SUCCESS; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output