aboutsummaryrefslogtreecommitdiff
path: root/astrftime.c
blob: 4c10654404f56ff24b90db3505ec15bcab13f0a5 (plain) (blame)
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
#define _POSIX_C_SOURCE 200809L

#include "utils.h"
#include <errno.h>
#include <locale.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

char *astrftime(const char *const fmt, const struct tm *const tm)
{
    char *ret = NULL, *s = NULL;
    size_t n = sizeof ".";
    const locale_t l = newlocale(LC_TIME_MASK, "POSIX", (locale_t)0);

    if (l == (locale_t)0)
    {
        fprintf(stderr, "%s: newlocale(3): %s\n", __func__, strerror(errno));
        goto end;
    }
    else if (!(s = malloc(n)))
    {
        fprintf(stderr, "%s: malloc(3): %s\n", __func__, strerror(errno));
        goto end;
    }

    for (;;)
    {
        const int res = strftime_l(s, n, fmt, tm, l);

        if (!res)
        {
            char *const ss = realloc(s, ++n);

            if (!s)
            {
                fprintf(stderr, "%s: realloc(3): %s\n", __func__,
                    strerror(errno));
                goto end;
            }

            s = ss;
        }
        else
            break;
    }

    ret = s;

end:

    if (!ret)
        free(s);

    freelocale(l);
    return ret;
}