This source file includes following definitions.
- _load_file
- load_file_to_length
- load_file
- process_file
- load_int_value_file
- save_int_value_file
1 #include "stdlib.h"
2 #include "stddef.h"
3 #include "string.h"
4 #include "fileutil.h"
5
6
7
8
9
10
11
12
13
14
15
16 static char* _load_file(const char* name, int* rv_size, int* st_size, int add0)
17 {
18 int fd;
19 int ssize = -1;
20 int rsize = -1;
21 char* buf = 0;
22
23 if (add0 != 0) add0 = 1;
24
25
26 struct stat st;
27 if (stat(name,&st) == 0)
28 {
29
30 ssize = st.st_size;
31 if ((st_size != 0) && (*st_size > 0) && (ssize > *st_size))
32 ssize = *st_size;
33 if (ssize > 0)
34 {
35
36 fd = open( name, O_RDONLY, 0777 );
37 if (fd >= 0)
38 {
39
40 char *ubuf = umalloc(512);
41 if (ubuf != 0)
42 {
43
44
45 buf = malloc(ssize+add0);
46 if (buf != 0)
47 {
48
49 int lsize = 0;
50 rsize = 0;
51 while (lsize < ssize)
52 {
53 int len = ssize - lsize;
54 if (len > 512) len = 512;
55 rsize += read(fd, ubuf, len);
56 memcpy(buf+lsize,ubuf,len);
57 lsize += len;
58 }
59 if (add0) buf[ssize] = 0;
60 }
61 ufree(ubuf);
62 }
63 close(fd);
64 }
65 }
66 }
67
68
69 if (rv_size) *rv_size = rsize;
70 if (st_size) *st_size = ssize;
71
72 return buf;
73 }
74
75
76
77
78
79
80
81 char* load_file_to_length(const char* name, int* rv_size, int add0, int length)
82 {
83 int rsize, ssize = length;
84
85 char* buf = _load_file(name, &rsize, &ssize, add0);
86
87 if (rv_size) *rv_size = rsize;
88
89 if (rsize != ssize)
90 {
91 if (buf) free(buf);
92 buf = 0;
93 if (rv_size) *rv_size = -1;
94 }
95
96 return buf;
97 }
98
99
100
101
102
103
104 char* load_file(const char* name, int* rv_size, int add0)
105 {
106 return load_file_to_length(name, rv_size, add0, 0);
107 }
108
109
110
111
112
113
114
115
116
117 int process_file(const char *filename, callback_process_file callback, int add0)
118 {
119 int size;
120
121 char *buf = load_file(filename, &size, add0);
122
123 size = callback(buf, size);
124
125 if (buf)
126 free(buf);
127
128 return size;
129 }
130
131
132
133
134
135
136 int load_int_value_file( const char* filename, int* value_p )
137 {
138 char *buf;
139
140 buf = load_file(filename, 0, 1);
141 if (!buf)
142 return 0;
143
144 if (value_p)
145 *value_p = strtol(buf, NULL, 10 );
146 free(buf);
147
148 return 1;
149 }
150
151
152
153 void save_int_value_file( const char* filename, int value )
154 {
155 char* buf = umalloc(20);
156 if ( !buf )
157 return;
158
159 sprintf(buf,"%d", value);
160
161 int fd = open( filename, O_WRONLY|O_CREAT|O_TRUNC, 0777);
162 if (fd>=0)
163 {
164 write(fd, buf, strlen(buf)+1);
165 close(fd);
166 }
167 ufree(buf);
168 }
169
170