ali@0
|
1 |
#include <stdlib.h>
|
ali@0
|
2 |
#include <stdio.h>
|
ali@5
|
3 |
#include <bl/macros.h>
|
ali@5
|
4 |
#include <bl/mem.h>
|
ali@5
|
5 |
#include <bl/fileutils.h>
|
ali@5
|
6 |
#include <bl/blstring.h>
|
ali@0
|
7 |
|
ali@0
|
8 |
/*
|
ali@0
|
9 |
* Read a file into memory (which should be freed with mem_free when no
|
ali@0
|
10 |
* longer required). Returns FALSE on error and outputs a suitable error
|
ali@0
|
11 |
* message to stderr.
|
ali@0
|
12 |
*/
|
ali@0
|
13 |
boolean file_get_contents(const char *filename,char **contents,size_t *length)
|
ali@0
|
14 |
{
|
ali@0
|
15 |
FILE *fp;
|
ali@0
|
16 |
size_t n;
|
ali@0
|
17 |
char *buffer;
|
ali@0
|
18 |
String *string;
|
ali@0
|
19 |
fp=fopen(filename,"rb");
|
ali@0
|
20 |
if (!fp)
|
ali@0
|
21 |
{
|
ali@0
|
22 |
perror(filename);
|
ali@0
|
23 |
return FALSE;
|
ali@0
|
24 |
}
|
ali@0
|
25 |
buffer=mem_new(char,1024);
|
ali@0
|
26 |
string=string_new(NULL);
|
ali@0
|
27 |
do
|
ali@0
|
28 |
{
|
ali@0
|
29 |
n=fread(buffer,1,1024,fp);
|
ali@0
|
30 |
if (n<0)
|
ali@0
|
31 |
{
|
ali@0
|
32 |
perror(filename);
|
ali@0
|
33 |
string_free(string,TRUE);
|
ali@0
|
34 |
mem_free(buffer);
|
ali@0
|
35 |
free(fp);
|
ali@0
|
36 |
return FALSE;
|
ali@0
|
37 |
}
|
ali@0
|
38 |
string_append_len(string,buffer,n);
|
ali@0
|
39 |
} while(n);
|
ali@0
|
40 |
mem_free(buffer);
|
ali@0
|
41 |
if (length)
|
ali@0
|
42 |
*length=string->len;
|
ali@0
|
43 |
*contents=string_free(string,FALSE);
|
ali@0
|
44 |
fclose(fp);
|
ali@0
|
45 |
return TRUE;
|
ali@0
|
46 |
}
|