summaryrefslogtreecommitdiff
path: root/src/print_file_contents.c
blob: b66321a71bd7ef327df40ea84b61a0ba30e086bd (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
// vim:ts=4:sw=4:expandtab

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <yajl/yajl_gen.h>
#include <yajl/yajl_version.h>
#include <sys/types.h>

#include <sys/fcntl.h>
#include <unistd.h>
#include <errno.h>
#include "i3status.h"

#define STRING_SIZE 10

void print_file_contents(yajl_gen json_gen, char *buffer, const char *title, const char *path, const char *format, const char *format_bad, const int max_chars) {
    const char *walk = format;
    char *outwalk = buffer;
    char *buf = scalloc(max_chars * sizeof(char) + 1);

    char *abs_path = resolve_tilde(path);
    int fd = open(abs_path, O_RDONLY);
    free(abs_path);

    INSTANCE(path);

    int n = -1;
    if (fd > -1) {
        n = read(fd, buf, max_chars);
        if (n != -1) {
            buf[n] = '\0';
        }
        (void)close(fd);
        START_COLOR("color_good");
    } else if (errno != 0) {
        walk = format_bad;
        START_COLOR("color_bad");
    }

    // remove newline chars
    char *src, *dst;
    for (src = dst = buf; *src != '\0'; src++) {
        *dst = *src;
        if (*dst != '\n') {
            dst++;
        }
    }
    *dst = '\0';

    char string_errno[STRING_SIZE];

    sprintf(string_errno, "%d", errno);

    placeholder_t placeholders[] = {
        {.name = "%title", .value = title},
        {.name = "%content", .value = buf},
        {.name = "%errno", .value = string_errno},
        {.name = "%error", .value = strerror(errno)}};

    const size_t num = sizeof(placeholders) / sizeof(placeholder_t);
    buffer = format_placeholders(walk, &placeholders[0], num);

    free(buf);

    END_COLOR;
    OUTPUT_FULL_TEXT(buffer);
    free(buffer);
}