bl/textfileutils.c
author ali <ali@juiblex.co.uk>
Thu May 30 20:27:48 2013 +0100 (2013-05-30)
changeset 75 dab0af6882ee
parent 13 eca715c100fe
permissions -rw-r--r--
Added tag 1.90 for changeset 411867e8e20b
ali@0
     1
#include <stdlib.h>
ali@0
     2
#include <stdio.h>
ali@5
     3
#include <bl/bl.h>
ali@0
     4
ali@0
     5
/*
ali@69
     6
 * Read a file into memory (which should be freed with g_free when no
ali@0
     7
 * longer required). Returns NULL on error and outputs a suitable error
ali@0
     8
 * message to stderr.
ali@13
     9
 * DOS-style line endings and UTF-8 BOM are handled transparently even
ali@13
    10
 * on platforms which don't normally use these formats.
ali@0
    11
 */
ali@6
    12
gboolean file_get_contents_text(const char *filename,char **contents,
ali@69
    13
  size_t *length,GError **err)
ali@0
    14
{
ali@0
    15
    int i;
ali@13
    16
    unsigned char *raw;
ali@69
    17
    gsize raw_length;
ali@6
    18
    GString *string;
ali@69
    19
    if (!g_file_get_contents(filename,(char **)&raw,&raw_length,err))
ali@0
    20
	return FALSE;
ali@6
    21
    string=g_string_new(NULL);
ali@13
    22
    i=0;
ali@13
    23
    if (raw_length>=3 && raw[0]==0xEF && raw[1]==0xBB && raw[2]==0xBF)
ali@13
    24
	i+=3;			/* Skip BOM (U+FEFF) */
ali@13
    25
    for(;i<raw_length;i++)
ali@0
    26
	if (raw[i]!='\r')
ali@6
    27
	    g_string_append_c(string,raw[i]);
ali@6
    28
    g_free(raw);
ali@0
    29
    if (length)
ali@0
    30
	*length=string->len;
ali@0
    31
    if (contents)
ali@6
    32
	*contents=g_string_free(string,FALSE);
ali@0
    33
    else
ali@6
    34
	g_string_free(string,TRUE);
ali@0
    35
    return TRUE;
ali@0
    36
}