]> git.sur5r.net Git - i3/i3status/blob - src/general.c
fix slurp(), it needs to read size-1 for the trailing NUL
[i3/i3status] / src / general.c
1 // vim:ts=8:expandtab
2 #include <sys/types.h>
3 #include <string.h>
4 #include <stdarg.h>
5 #include <stdio.h>
6 #include <stdlib.h>
7 #include <unistd.h>
8 #include <sys/fcntl.h>
9
10 #include "i3status.h"
11
12 /*
13  * Reads size bytes into the destination buffer from filename.
14  *
15  */
16 bool slurp(const char *filename, char *destination, int size) {
17         int fd;
18
19         if ((fd = open(filename, O_RDONLY)) == -1)
20                 return false;
21
22         /* We need one byte for the trailing 0 byte */
23         int n = read(fd, destination, size-1);
24         if (n != -1)
25                 destination[n] = '\0';
26         (void)close(fd);
27
28         return true;
29 }
30
31 /*
32  * Skip the given character for exactly 'amount' times, returns
33  * a pointer to the first non-'character' character in 'input'.
34  *
35  */
36 char *skip_character(char *input, char character, int amount) {
37         char *walk;
38         size_t len = strlen(input);
39         int blanks = 0;
40
41         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
42                 if (*walk == character)
43                         blanks++;
44
45         return (walk == input ? walk : walk-1);
46 }
47
48 /*
49  * Write errormessage to statusbar and exit
50  *
51  */
52 void die(const char *fmt, ...) {
53         char buffer[512];
54         va_list ap;
55         va_start(ap, fmt);
56         (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
57         va_end(ap);
58
59         fprintf(stderr, "%s", buffer);
60         exit(EXIT_FAILURE);
61 }