-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile.c
More file actions
52 lines (40 loc) · 1.21 KB
/
file.c
File metadata and controls
52 lines (40 loc) · 1.21 KB
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 <stdio.h>
#include "util.h"
#include "file.h"
#include "vec.h"
#define STEP 256
/* vbuf is a vector */
int read_line_v(FILE *f, char *vbuf)
{
int err = 0;
size_t idx = 0;
size_t bytes;
vec__reserve(vbuf, STEP);
while ((bytes = fread(__vec__at(vbuf, idx), vec__mem_size(vbuf), min(vec__cap(vbuf) - idx, STEP), f))) {
size_t pre_idx = idx;
char *vbuf_raw = NULL;
idx += bytes;
vec__len_inc(vbuf, bytes / vec__mem_size(vbuf));
/* check if there's a newline */
vbuf_raw = __vec__at(vbuf, 0);
for (size_t i = pre_idx; i < idx; i++) {
if (vbuf_raw[i] == '\n') {
size_t new_size = i / vec__mem_size(vbuf);
vec__resize(vbuf, new_size);
goto read_out;
}
}
if (vec__cap(vbuf) == idx) {
if (vec__alloc(vbuf, STEP))
return -1;
}
}
read_out:
// insert null term
if (vec__cap(vbuf) >= vec__len(vbuf) + 1)
((char *)__vec__at(vbuf, 0))[vec__len(vbuf)] = 0;
else
*((char *)__vec__at(vbuf, vec__cap(vbuf) - 1)) = '\0';
pr_debug("Read line: \" %s \"\n", (char *)__vec__at(vbuf, 0));
return 0;
}