]> git.lizzy.rs Git - nothing.git/blob - src/system/line_stream.c
Merge pull request #571 from lastedge/patch-1
[nothing.git] / src / system / line_stream.c
1 #include <assert.h>
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <errno.h>
5 #include <string.h>
6
7 #include "line_stream.h"
8 #include "lt.h"
9 #include "lt/lt_adapters.h"
10 #include "system/nth_alloc.h"
11 #include "system/log.h"
12
13 struct LineStream
14 {
15     Lt *lt;
16     FILE *stream;
17     char *buffer;
18     size_t capacity;
19 };
20
21 LineStream *create_line_stream(const char *filename,
22                                const char *mode,
23                                size_t capacity)
24 {
25     assert(filename);
26     assert(mode);
27
28     Lt *lt = create_lt();
29     if (lt == NULL) {
30         return NULL;
31     }
32
33     LineStream *line_stream = PUSH_LT(
34         lt,
35         nth_alloc(sizeof(LineStream)),
36         free);
37     if (line_stream == NULL) {
38         RETURN_LT(lt, NULL);
39     }
40     line_stream->lt = lt;
41
42     line_stream->stream = PUSH_LT(
43         lt,
44         fopen(filename, mode),
45         fclose_lt);
46     if (line_stream->stream == NULL) {
47         log_fail("Could not open file '%s': %s\n", filename, strerror(errno));
48         RETURN_LT(lt, NULL);
49     }
50
51     line_stream->buffer = PUSH_LT(
52         lt,
53         nth_alloc(sizeof(char) * capacity),
54         free);
55     if (line_stream->buffer == NULL) {
56         RETURN_LT(lt, NULL);
57     }
58
59     line_stream->capacity = capacity;
60
61     return line_stream;
62 }
63
64 void destroy_line_stream(LineStream *line_stream)
65 {
66     assert(line_stream);
67
68     RETURN_LT0(line_stream->lt);
69 }
70
71 const char *line_stream_next(LineStream *line_stream)
72 {
73     assert(line_stream);
74     return fgets(line_stream->buffer,
75                  (int) line_stream->capacity,
76                  line_stream->stream);
77 }