aboutsummaryrefslogtreecommitdiff
path: root/util/err.c
blob: 1f3fb6d1ec0839fb23852fb2c32d1df1689f42bf (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#include "util.h"

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

#define FORMAT_MAX_SIZE 1024

extern int errno;

void NORETURN die(char const * format, ...) {
	va_list vargs;
	va_start (vargs, format);

	vfprintf(stderr, format, vargs);
	fprintf(stderr, "\n");

	va_end(vargs);
	exit(1);
}

void err(char const * format, ...) {
	va_list vargs;
	va_start (vargs, format);

	vfprintf(stderr, format, vargs);
	fprintf(stderr, "\n");

	va_end(vargs);
}

void format_with_errno(char * buf, size_t n, char const * format) {
	char const * errstr = strerror(errno);
	char fmt_err[256];

	size_t i = 0,
		   j = 0;
	while(errstr[j] && i < sizeof(fmt_err) - 1) {
		if((fmt_err[i++] = errstr[j++]) != '%')
			continue;

		if(i < sizeof(fmt_err) - 1) {
			fmt_err[i++] = '%';
		} else {
			i--;
		}
	}

	fmt_err[i] = '\0';

	snprintf(buf, n, "%s: %s", format, fmt_err);
}


void NORETURN die_errno(char const * format, ...) {
	va_list vargs;
	va_start (vargs, format);

	char buf[FORMAT_MAX_SIZE];
	format_with_errno(buf, sizeof(buf), format);
	vfprintf(stderr, buf, vargs);
	fprintf(stderr, "\n");
	exit(1);

	va_end(vargs);
}

void err_errno(char const * format, ...) {
	va_list vargs;
	va_start (vargs, format);

	char buf[FORMAT_MAX_SIZE];

	format_with_errno(buf, sizeof(buf), format);
	vfprintf(stderr, buf, vargs);
	fprintf(stderr, "\n");
	
	va_end(vargs);
}