gclib/fileutils.c
changeset 0 c2f4c0285180
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/gclib/fileutils.c	Tue Jan 24 23:54:05 2012 +0000
     1.3 @@ -0,0 +1,46 @@
     1.4 +#include <stdlib.h>
     1.5 +#include <stdio.h>
     1.6 +#include <gclib/macros.h>
     1.7 +#include <gclib/mem.h>
     1.8 +#include <gclib/fileutils.h>
     1.9 +#include <gclib/gcstring.h>
    1.10 +
    1.11 +/*
    1.12 + * Read a file into memory (which should be freed with mem_free when no
    1.13 + * longer required). Returns FALSE on error and outputs a suitable error
    1.14 + * message to stderr.
    1.15 + */
    1.16 +boolean file_get_contents(const char *filename,char **contents,size_t *length)
    1.17 +{
    1.18 +    FILE *fp;
    1.19 +    size_t n;
    1.20 +    char *buffer;
    1.21 +    String *string;
    1.22 +    fp=fopen(filename,"rb");
    1.23 +    if (!fp)
    1.24 +    {
    1.25 +	perror(filename);
    1.26 +	return FALSE;
    1.27 +    }
    1.28 +    buffer=mem_new(char,1024);
    1.29 +    string=string_new(NULL);
    1.30 +    do
    1.31 +    {
    1.32 +	n=fread(buffer,1,1024,fp);
    1.33 +	if (n<0)
    1.34 +	{
    1.35 +	    perror(filename);
    1.36 +	    string_free(string,TRUE);
    1.37 +	    mem_free(buffer);
    1.38 +	    free(fp);
    1.39 +	    return FALSE;
    1.40 +	}
    1.41 +	string_append_len(string,buffer,n);
    1.42 +    } while(n);
    1.43 +    mem_free(buffer);
    1.44 +    if (length)
    1.45 +	*length=string->len;
    1.46 +    *contents=string_free(string,FALSE);
    1.47 +    fclose(fp);
    1.48 +    return TRUE;
    1.49 +}