]> git.sur5r.net Git - i3/i3status/blob - src/general.c
slurp(): null-terminate buffer (Thanks mist)
[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         int n = read(fd, destination, size);
23         if (n != -1)
24                 destination[n] = '\0';
25         (void)close(fd);
26
27         return true;
28 }
29
30 /*
31  * Skip the given character for exactly 'amount' times, returns
32  * a pointer to the first non-'character' character in 'input'.
33  *
34  */
35 char *skip_character(char *input, char character, int amount) {
36         char *walk;
37         size_t len = strlen(input);
38         int blanks = 0;
39
40         for (walk = input; ((size_t)(walk - input) < len) && (blanks < amount); walk++)
41                 if (*walk == character)
42                         blanks++;
43
44         return (walk == input ? walk : walk-1);
45 }
46
47 /*
48  * Write errormessage to statusbar and exit
49  *
50  */
51 void die(const char *fmt, ...) {
52         char buffer[512];
53         va_list ap;
54         va_start(ap, fmt);
55         (void)vsnprintf(buffer, sizeof(buffer), fmt, ap);
56         va_end(ap);
57
58         fprintf(stderr, "%s", buffer);
59         exit(EXIT_FAILURE);
60 }