bl/textfileutils.c
author ali <ali@juiblex.co.uk>
Tue Oct 15 09:16:04 2013 +0100 (2013-10-15)
changeset 100 ad92d11d59b8
parent 13 eca715c100fe
permissions -rw-r--r--
Fix bug #27: Don't treat [1] as a standalone 1
     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 g_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,GError **err)
    14 {
    15     int i;
    16     unsigned char *raw;
    17     gsize raw_length;
    18     GString *string;
    19     if (!g_file_get_contents(filename,(char **)&raw,&raw_length,err))
    20 	return FALSE;
    21     string=g_string_new(NULL);
    22     i=0;
    23     if (raw_length>=3 && raw[0]==0xEF && raw[1]==0xBB && raw[2]==0xBF)
    24 	i+=3;			/* Skip BOM (U+FEFF) */
    25     for(;i<raw_length;i++)
    26 	if (raw[i]!='\r')
    27 	    g_string_append_c(string,raw[i]);
    28     g_free(raw);
    29     if (length)
    30 	*length=string->len;
    31     if (contents)
    32 	*contents=g_string_free(string,FALSE);
    33     else
    34 	g_string_free(string,TRUE);
    35     return TRUE;
    36 }