Skip to content

Instantly share code, notes, and snippets.

@mizdra
Last active August 3, 2019 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mizdra/2ef896186de5bfc071f6820870615336 to your computer and use it in GitHub Desktop.
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)
#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;
}
}
#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;
}
@mizdra
Copy link
Author

mizdra commented Aug 3, 2019

Output

$ clang -Wall -Wextra -Werror -pedantic-errors -Wno-pragma-once-outside-header -Wno-gnu-zero-variadic-macro-arguments -std=gnu11 -g main.c -o main
$ ./main
error: fail to open file
 --> `print_file_header` (main.c:11)
 = errno: No such file or directory(2)
panic: failt to `print_file_header`
 --> `main` (main.c:25)

output

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment