Break out more similarities between showlog.c and import.c
[nagios-reports-module.git] / lparse.c
blob9511e33d7a8429e7ec0461b04459e4614b34c503
1 #define _GNU_SOURCE 1
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <unistd.h>
5 #include <string.h>
6 #include <errno.h>
7 #include <sys/types.h>
8 #include <sys/stat.h>
9 #include <fcntl.h>
10 #include "lparse.h"
12 static char *buf;
13 #define MAX_BUF ((512 * 1024) - 1)
15 int lparse_fd(int fd, size_t size, int (*parse)(char *, size_t))
17 size_t tot_rd = 0, parsed = 0;
19 if (!buf && !(buf = calloc(1, MAX_BUF + 1)))
20 return -1;
22 while (tot_rd < size) {
23 char *next, *cur;
24 int bytes_rd;
25 size_t blkparsed;
27 bytes_rd = read(fd, buf, MAX_BUF < size ? MAX_BUF : size);
28 if (bytes_rd < 0)
29 return -1;
31 if (tot_rd + bytes_rd < size) {
32 /* rewind the file to the last found newline */
33 while (buf[bytes_rd - 1] != '\n')
34 bytes_rd--;
35 lseek(fd, tot_rd + bytes_rd, SEEK_SET);
37 tot_rd += bytes_rd;
39 /* set a sentinel for memchr() */
40 buf[bytes_rd] = '\n';
42 cur = buf;
43 for (blkparsed = 0; blkparsed < bytes_rd; cur = next + 1) {
44 size_t len;
45 next = memchr(cur, '\n', bytes_rd + 1 - blkparsed);
46 len = next - cur;
47 blkparsed += len + 1;
49 cur[len] = '\0';
50 parse(cur, len);
52 parsed += cur - buf;
55 return 0;
58 int lparse_path(const char *path, size_t size, int (*parse)(char *, size_t))
60 int fd, result;
62 /* zero size files are never interesting */
63 if (!size)
64 return 0;
66 if ((fd = open(path, O_RDONLY)) < 0)
67 return -1;
69 result = lparse_fd(fd, size, parse);
71 close(fd);
73 return result;