1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
|
#include <stdlib.h>
#include <stdio.h>
#include "util.h"
/* Put the entire file content into the string str and the file size
into *len.
If errors occur, return non-zero; otherwise the return value is
zero.
Note that *str should be already allocated.
Note that the length of the string str is actually 1+length, and
the last character is the null character. */
BOOL
read_entire_file(const char *file_name, char **str, NUM *len)
{
long file_size = 0;
FILE *file = fopen(file_name, "r");
if (!file) {
eprintf("%s:%Cannot open file \"%s\": ",
__FILE__, __LINE__, file_name);
perror(NULL);
return 1;
}
fseek(file, 0, SEEK_END);
file_size = ftell(file);
fseek(file, 0, SEEK_SET);
*len = 1+file_size;
char *newstr = realloc(*str, 1+file_size);
if (newstr == NULL) {
fleprintf0("Cannot realloc\n");
return 1;
}
*str = newstr;
fread(*str, sizeof(char), file_size, file);
fclose(file);
*(*str+file_size) = 0;
return 0;
}
|