-
Notifications
You must be signed in to change notification settings - Fork 0
/
log_read.c
59 lines (42 loc) · 925 Bytes
/
log_read.c
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
52
53
54
55
56
57
58
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "log_read.h"
void log_read_lines (FILE *input, void (*emit)(char *, void *), void *data) {
int ch;
char *buffer = NULL;
size_t cursor = 0;
size_t length = 0;
#define BUFFER_SIZE (4096)
setvbuf (input, NULL, _IOLBF, BUFFER_SIZE);
while ((ch = fgetc (input)) != EOF) {
if (!buffer) {
buffer = malloc (BUFFER_SIZE);
if (!buffer) {
return;
}
cursor = 0;
length = BUFFER_SIZE;
memset (buffer, '\0', length);
}
if (ch == '\n') {
(*emit) (buffer, data);
buffer = NULL;
} else {
buffer[cursor++] = ch;
if (cursor >= length) {
char *tmp = NULL;
size_t increase = length;
length = length + increase;
tmp = realloc (buffer, length);
if (!tmp) {
free (buffer);
return;
}
buffer = tmp;
memset (buffer + increase, '\0', increase);
}
}
}
#undef BUFFER_SIZE
}