bl/fileutils.c
author ali <ali@juiblex.co.uk>
Fri Jan 27 10:30:16 2012 +0000 (2012-01-27)
changeset 5 f600b0d1fc5d
parent 0 gclib/fileutils.c@c2f4c0285180
permissions -rw-r--r--
Rename to bookloupe
     1 #include <stdlib.h>
     2 #include <stdio.h>
     3 #include <bl/macros.h>
     4 #include <bl/mem.h>
     5 #include <bl/fileutils.h>
     6 #include <bl/blstring.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 }