]> git.sur5r.net Git - i3/i3status/blob - src/print_file_contents.c
Added function to print content from file (#331)
[i3/i3status] / src / print_file_contents.c
1 // vim:ts=4:sw=4:expandtab
2
3 #include <stdio.h>
4 #include <stdlib.h>
5 #include <string.h>
6 #include <yajl/yajl_gen.h>
7 #include <yajl/yajl_version.h>
8 #include <sys/types.h>
9
10 #include <sys/fcntl.h>
11 #include <unistd.h>
12 #include <errno.h>
13 #include "i3status.h"
14
15 static void *scalloc(size_t size) {
16     void *result = calloc(size, 1);
17     if (result == NULL) {
18         die("Error: out of memory (calloc(%zu))\n", size);
19     }
20     return result;
21 }
22
23 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) {
24     const char *walk = format;
25     char *outwalk = buffer;
26     char *buf = scalloc(max_chars * sizeof(char));
27
28     int n = -1;
29     int fd = open(path, O_RDONLY);
30
31     INSTANCE(path);
32
33     if (fd > -1) {
34         n = read(fd, buf, max_chars);
35         if (n != -1) {
36             buf[n] = '\0';
37         }
38         (void)close(fd);
39         START_COLOR("color_good");
40     } else if (errno != 0) {
41         walk = format_bad;
42         START_COLOR("color_bad");
43     }
44
45     for (; *walk != '\0'; walk++) {
46         if (*walk != '%') {
47             *(outwalk++) = *walk;
48         } else if (BEGINS_WITH(walk + 1, "title")) {
49             outwalk += sprintf(outwalk, "%s", title);
50             walk += strlen("title");
51         } else if (BEGINS_WITH(walk + 1, "content")) {
52             for (char *s = buf; *s != '\0' && n > 0; s++, n--) {
53                 if (*s != '\n') {
54                     *(outwalk++) = *s;
55                 }
56             }
57             walk += strlen("content");
58         } else if (BEGINS_WITH(walk + 1, "errno")) {
59             outwalk += sprintf(outwalk, "%d", errno);
60             walk += strlen("errno");
61         } else if (BEGINS_WITH(walk + 1, "error")) {
62             outwalk += sprintf(outwalk, "%s", strerror(errno));
63             walk += strlen("error");
64         } else {
65             *(outwalk++) = '%';
66         }
67     }
68
69     free(buf);
70
71     END_COLOR;
72     OUTPUT_FULL_TEXT(buffer);
73 }