X-Git-Url: http://pileus.org/git/?p=lackey;a=blobdiff_plain;f=src%2Futil.c;h=37b004d94896899b95312fdc3abc387fe5d725b6;hp=197f3d8ea17ca09f95b485701357d296feb1190c;hb=f45d7e37ac9dd4e70a89671edf862a868f8ab343;hpb=cfe3c8f203bd937ca4cadf7ef6c1bd9b2c603e13 diff --git a/src/util.c b/src/util.c index 197f3d8..37b004d 100644 --- a/src/util.c +++ b/src/util.c @@ -1,5 +1,5 @@ /* - * Copyright (C) 2012,2013 Andy Spencer + * Copyright (C) 2012-2013 Andy Spencer * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -45,6 +45,7 @@ static void message(FILE *output_fd, const char *prefix, const char *fmt, va_lis fprintf(output_fd, "%s: ", prefix); vfprintf(output_fd, fmt, tmp); fprintf(output_fd, "\n"); + fflush(output_fd); } /* Log to debug file */ @@ -53,6 +54,7 @@ static void message(FILE *output_fd, const char *prefix, const char *fmt, va_lis fprintf(debug_fd, "%s: ", prefix); vfprintf(debug_fd, fmt, tmp); fprintf(debug_fd, "\n"); + fflush(debug_fd); } /* Log to status bar */ @@ -109,6 +111,39 @@ void *alloc0(int size) return data; } +/* File functions */ +char *read_file(const char *path, int *len) +{ + /* we could use stat, but we'll try to be portable */ + FILE *fd = fopen(path, "rt+"); + if (!fd) + return NULL; + + int block = 512; // read size + int size = 512; // buffer size + int slen = 0; // string length + char *buf = malloc(size); + if (!buf) + goto err; + + while (!feof(fd)) { + if (slen + block + 1 > size) { + size *= 2; + buf = realloc(buf, size); + if (!buf) + goto err; + } + slen += fread(&buf[slen], 1, block, fd); + buf[slen] = '\0'; + } + +err: + if (len) + *len = slen; + fclose(fd); + return buf; +} + /* Debugging functions */ void debug(char *fmt, ...) {