bl/textfileutils.c
author ali <ali@juiblex.co.uk>
Mon Feb 20 10:10:48 2012 +0000 (2012-02-20)
changeset 37 037942e1bc4f
parent 6 faab25d520dd
child 69 1016349e619f
permissions -rw-r--r--
Add end of word scannos to testcase
     1 #include <stdlib.h>
     2 #include <stdio.h>
     3 #include <bl/bl.h>
     4 
     5 /*
     6  * Read a file into memory (which should be freed with mem_free when no
     7  * longer required). Returns NULL on error and outputs a suitable error
     8  * message to stderr.
     9  * DOS-style line endings and UTF-8 BOM are handled transparently even
    10  * on platforms which don't normally use these formats.
    11  */
    12 gboolean file_get_contents_text(const char *filename,char **contents,
    13   size_t *length)
    14 {
    15     int i;
    16     unsigned char *raw;
    17     size_t raw_length;
    18     GString *string;
    19     GError *error=NULL;
    20     if (!g_file_get_contents(filename,(char *)&raw,&raw_length,&error))
    21     {
    22 	fprintf(stderr,"%s: %s\n",filename,error->message);
    23 	g_error_free(error);
    24 	return FALSE;
    25     }
    26     string=g_string_new(NULL);
    27     i=0;
    28     if (raw_length>=3 && raw[0]==0xEF && raw[1]==0xBB && raw[2]==0xBF)
    29 	i+=3;			/* Skip BOM (U+FEFF) */
    30     for(;i<raw_length;i++)
    31 	if (raw[i]!='\r')
    32 	    g_string_append_c(string,raw[i]);
    33     g_free(raw);
    34     if (length)
    35 	*length=string->len;
    36     if (contents)
    37 	*contents=g_string_free(string,FALSE);
    38     else
    39 	g_string_free(string,TRUE);
    40     return TRUE;
    41 }