bl/textfileutils.c
author ali <ali@juiblex.co.uk>
Mon Jan 30 23:32:47 2012 +0000 (2012-01-30)
changeset 11 4a80c6053a66
parent 5 f600b0d1fc5d
child 13 eca715c100fe
permissions -rw-r--r--
Use Unicode output on MS-Windows consoles
     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 are handled transparently even on platforms which
    10  * don't normally use this format.
    11  */
    12 gboolean file_get_contents_text(const char *filename,char **contents,
    13   size_t *length)
    14 {
    15     int i;
    16     char *raw;
    17     size_t raw_length;
    18     GString *string;
    19     GError *error=NULL;
    20     if (!g_file_get_contents(filename,&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     for(i=0;i<raw_length;i++)
    28 	if (raw[i]!='\r')
    29 	    g_string_append_c(string,raw[i]);
    30     g_free(raw);
    31     if (length)
    32 	*length=string->len;
    33     if (contents)
    34 	*contents=g_string_free(string,FALSE);
    35     else
    36 	g_string_free(string,TRUE);
    37     return TRUE;
    38 }