gclib/fileutils.c
author ali <ali@juiblex.co.uk>
Tue Jan 24 23:54:05 2012 +0000 (2012-01-24)
changeset 0 c2f4c0285180
permissions -rw-r--r--
Initial version
     1 #include <stdlib.h>
     2 #include <stdio.h>
     3 #include <gclib/macros.h>
     4 #include <gclib/mem.h>
     5 #include <gclib/fileutils.h>
     6 #include <gclib/gcstring.h>
     7 
     8 /*
     9  * Read a file into memory (which should be freed with mem_free when no
    10  * longer required). Returns FALSE on error and outputs a suitable error
    11  * message to stderr.
    12  */
    13 boolean file_get_contents(const char *filename,char **contents,size_t *length)
    14 {
    15     FILE *fp;
    16     size_t n;
    17     char *buffer;
    18     String *string;
    19     fp=fopen(filename,"rb");
    20     if (!fp)
    21     {
    22 	perror(filename);
    23 	return FALSE;
    24     }
    25     buffer=mem_new(char,1024);
    26     string=string_new(NULL);
    27     do
    28     {
    29 	n=fread(buffer,1,1024,fp);
    30 	if (n<0)
    31 	{
    32 	    perror(filename);
    33 	    string_free(string,TRUE);
    34 	    mem_free(buffer);
    35 	    free(fp);
    36 	    return FALSE;
    37 	}
    38 	string_append_len(string,buffer,n);
    39     } while(n);
    40     mem_free(buffer);
    41     if (length)
    42 	*length=string->len;
    43     *contents=string_free(string,FALSE);
    44     fclose(fp);
    45     return TRUE;
    46 }