| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
#include <glib.h> |
| 10 |
|
| 11 |
#include <sys/types.h> |
| 12 |
#include <sys/stat.h> |
| 13 |
#include <fcntl.h> |
| 14 |
#include <unistd.h> |
| 15 |
#include <stdio.h> |
| 16 |
#include <stdlib.h> |
| 17 |
#include <string.h> |
| 18 |
#include <errno.h> |
| 19 |
|
| 20 |
|
| 21 |
gchar **trc_open(gchar *fname) |
| 22 |
{ |
| 23 |
gint fd; |
| 24 |
struct stat fds; |
| 25 |
ssize_t rb; |
| 26 |
gchar *rc, **rcs; |
| 27 |
|
| 28 |
if ((fd=open(fname, O_RDONLY)) == -1) { |
| 29 |
fprintf(stderr, "%s: open() %s failed: %s\n", __FUNCTION__, fname, strerror(errno)); |
| 30 |
return NULL; |
| 31 |
} |
| 32 |
if ((fstat(fd, &fds)) == -1) { |
| 33 |
close(fd); |
| 34 |
fprintf(stderr, "%s: fstat() failed: %s\n", __FUNCTION__, strerror(errno)); |
| 35 |
return NULL; |
| 36 |
} |
| 37 |
if (!(fds.st_size)) { |
| 38 |
close(fd); |
| 39 |
fprintf(stderr, "%s: zero length file.\n", __FUNCTION__); |
| 40 |
return NULL; |
| 41 |
} |
| 42 |
if (!(rc=malloc(fds.st_size+1))) { |
| 43 |
close(fd); |
| 44 |
fprintf(stderr, "%s: malloc() failed: cannot alloc %d bytes\n", __FUNCTION__, (int)fds.st_size); |
| 45 |
return NULL; |
| 46 |
} |
| 47 |
if ((rb=read(fd, rc, fds.st_size)) != fds.st_size) { |
| 48 |
free(rc); |
| 49 |
close(fd); |
| 50 |
if (rb == -1) { |
| 51 |
fprintf(stderr, "%s: read() failed: %s\n", __FUNCTION__, strerror(errno)); |
| 52 |
} else { |
| 53 |
fprintf(stderr, "%s: read() reads less bytes than expected =/\n", __FUNCTION__); |
| 54 |
} |
| 55 |
return NULL; |
| 56 |
} |
| 57 |
rc[fds.st_size]=0; |
| 58 |
close(fd); |
| 59 |
rcs=g_strsplit(rc, "\n", 0); |
| 60 |
free(rc); |
| 61 |
return rcs; |
| 62 |
} |
| 63 |
|
| 64 |
|
| 65 |
void trc_close(gchar **rcs) { |
| 66 |
if (rcs) { |
| 67 |
g_strfreev(rcs); |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
|
| 72 |
gchar *trc_get_str(gchar **rcs, gchar *param) |
| 73 |
{ |
| 74 |
gint i; |
| 75 |
gchar **strval,*val; |
| 76 |
|
| 77 |
if (!rcs) { |
| 78 |
fprintf(stderr, "%s called with uninitialised rcs. strange. \n", __FUNCTION__); |
| 79 |
return NULL; |
| 80 |
} |
| 81 |
if (!param) { |
| 82 |
fprintf(stderr, "%s called with NULL param. strange. \n", __FUNCTION__); |
| 83 |
return NULL; |
| 84 |
} |
| 85 |
for (i=0;rcs[i];i++) { |
| 86 |
if (rcs[i][0] && rcs[i][0]!='#' && (strval=g_strsplit(rcs[i],"=",2)) && strval[0] && strval[1]) { |
| 87 |
if (!(strcmp(g_strstrip(strval[0]),param))) { |
| 88 |
val=g_strdup(g_strstrip(strval[1])); |
| 89 |
g_strfreev(strval); |
| 90 |
return val; |
| 91 |
} |
| 92 |
g_strfreev(strval); |
| 93 |
} |
| 94 |
} |
| 95 |
return NULL; |
| 96 |
} |
| 97 |
|
| 98 |
|
| 99 |
gint trc_get_uint(gchar **rcs, gchar *param) { |
| 100 |
gchar *val; |
| 101 |
gint ret; |
| 102 |
|
| 103 |
if (!(val=trc_get_str(rcs, param))) { |
| 104 |
return -1; |
| 105 |
} |
| 106 |
ret = atoi(val); |
| 107 |
g_free (val); |
| 108 |
return ret; |
| 109 |
} |