err 2.0.0
Small error-printing library written in C
Loading...
Searching...
No Matches
weekday.c
1/**
2 * @example weekday.c
3 * This example demonstrates how the library makes it easy to concisely express
4 * repetitive errors.
5 */
6
7#include <stdio.h>
8#include <stdlib.h>
9#include <string.h>
10#include <time.h>
11
12#include "../err.h"
13
14void
15usage(void)
16{
17 fputs("usage: weekday YYYY-MM-DD\n", stderr);
18}
19
20int
21main(int argc, char *argv[])
22{
23 struct tm tm = {0};
24 char *temp;
25 int year, month, day;
26 char linebuf[64];
27
29
30 if (argc != 2) {
31 usage();
32 return EXIT_FAILURE;
33 }
34
35 /* Note that when errno == 0, strerror(errno) is not included in
36 * the output of err(). */
37
38 if ((temp = strtok(argv[1], "-")) == NULL)
39 err("bad date: no year");
40 else if ((year = atoi(temp)) == 0)
41 err("bad date: invalid year");
42
43 if ((temp = strtok(NULL, "-")) == NULL)
44 err("bad date: no month");
45 else if ((month = atoi(temp)) == 0)
46 err("bad date: invalid month");
47
48 if ((temp = strtok(NULL, "-")) == NULL)
49 err("bad date: no day");
50 else if ((day = atoi(temp)) == 0)
51 err("bad date: invalid day");
52
53 /* See ctime(3) */
54 tm.tm_year = year - 1900;
55 tm.tm_mon = month - 1;
56 tm.tm_mday = day;
57
58 if (mktime(&tm) == (time_t)-1)
59 err("mktime failed");
60
61 strftime(linebuf, sizeof(linebuf), "%Y-%m-%d: %A", &tm);
62 puts(linebuf);
63
64 return EXIT_SUCCESS;
65}
char * program_invocation_name
Global value for the program's name.
Definition: err.c:29
void err(const char *fmt,...)
Prints a formatted error message to stderr and exits.
Definition: err.c:123