wmclockmon: rename `DFLAGS` `debug_CFLAGS`
[dockapps.git] / wmclockmon / wmclockmon-cal / tools.c
blob61e4067fb89bf204908a96cc4ebcddbbe73f8e0d
1 /*
2 * Tools : memory management, file loading and saving
3 */
5 #include "../config.h"
6 #include "defines.h"
7 #include "tools.h"
8 #include <stdio.h>
9 #include <stdlib.h>
10 #include <string.h>
11 #include <strings.h>
12 #include <sys/types.h>
13 #include <ctype.h>
14 #include <pwd.h>
15 #include <unistd.h>
16 #include <sys/types.h>
19 int fexist(const char *filename) {
20 FILE *file;
22 if ( (file = fopen(filename, "r") ) == NULL) return FALSE;
23 fclose(file);
25 return TRUE;
29 void *xmalloc(size_t size) {
30 void *ret = malloc(size);
31 if (ret == NULL) {
32 perror("malloc() ");
33 exit(-1);
34 } else
35 return ret;
39 char *xstrdup(const char *string) {
40 char *ret = strdup(string);
41 if (ret == NULL) {
42 perror("strdup() ");
43 exit(-1);
44 } else
45 return ret;
49 int getbool(char *value) {
50 int i;
51 for (i = 0 ; value[i] ; i++) value[i] = tolower(value[i]);
52 if (strcmp(value, "0") == 0) return FALSE;
53 if (strcmp(value, "1") == 0) return TRUE;
54 if (strcmp(value, "true") == 0) return TRUE;
55 if (strcmp(value, "false") == 0) return FALSE;
56 if (strcmp(value, "yes") == 0) return TRUE;
57 if (strcmp(value, "no") == 0) return FALSE;
58 if (strcmp(value, "on") == 0) return TRUE;
59 if (strcmp(value, "off") == 0) return FALSE;
60 printf("Error in converting \"%s\" to boolean value.\n", value);
61 return FALSE;
65 char *robust_home() {
66 if (getenv("HOME"))
67 return getenv("HOME");
68 else if (getenv("USER") && getpwnam(getenv("USER")))
69 return getpwnam (getenv ("USER") )->pw_dir;
70 else if (getenv ("LOGNAME") && getpwnam(getenv("LOGNAME")))
71 return getpwnam(getenv("LOGNAME"))->pw_dir;
72 else if ((getuid() != -1) && (getpwuid(getuid())))
73 return getpwuid(getuid())->pw_dir;
74 else
75 return "/";
79 char *get_file(const char *datestr) {
80 char *Home = robust_home();
81 int len = strlen(Home) + strlen(DEFAULT_CONFIGDIR) + strlen(datestr);
82 char *filename = xmalloc(len + 3);
84 sprintf(filename, "%s/%s/%s", Home, DEFAULT_CONFIGDIR, datestr);
85 return filename;