1 #include "system/stacktrace.h"
8 #include "line_stream.h"
10 #include "lt_adapters.h"
11 #include "system/nth_alloc.h"
12 #include "system/log.h"
13 #include "system/str.h"
24 // TODO(#905): create_line_stream probably does not need mode
25 // Because LineStream interface doesn't even have anything
26 // for writing to files. So we can just hardcode the mode
27 // inside of the ctor.
28 LineStream *create_line_stream(const char *filename,
32 trace_assert(filename);
37 LineStream *line_stream = PUSH_LT(
39 nth_calloc(1, sizeof(LineStream)),
41 if (line_stream == NULL) {
46 line_stream->stream = PUSH_LT(
48 fopen(filename, mode),
50 if (line_stream->stream == NULL) {
51 log_fail("Could not open file '%s': %s\n", filename, strerror(errno));
55 line_stream->buffer = PUSH_LT(
57 nth_calloc(1, sizeof(char) * capacity),
59 if (line_stream->buffer == NULL) {
63 line_stream->capacity = capacity;
64 line_stream->unfinished = false;
69 void destroy_line_stream(LineStream *line_stream)
71 trace_assert(line_stream);
73 RETURN_LT0(line_stream->lt);
77 const char *line_stream_next_chunk(LineStream *line_stream)
79 trace_assert(line_stream);
81 const char *s = fgets(line_stream->buffer,
82 (int) line_stream->capacity,
88 line_stream->unfinished = s[n - 1] != '\n';
93 const char *line_stream_next(LineStream *line_stream)
95 trace_assert(line_stream);
97 while (line_stream->unfinished) {
98 line_stream_next_chunk(line_stream);
101 return line_stream_next_chunk(line_stream);
104 char *line_stream_collect_n_lines(LineStream *line_stream, size_t n)
106 char *result = string_append(NULL, "");
107 for (size_t i = 0; i < n; ++i) {
108 const char *line = line_stream_next(line_stream);
114 result = string_append(result, line);
120 char *line_stream_collect_until_end(LineStream *line_stream)
122 char *result = string_append(NULL, "");
123 const char *line = line_stream_next(line_stream);
125 /* TODO(#906): line_stream_collect_until_end does not distinguish between EOF and error during reading */
126 while (line != NULL) {
127 result = string_append(result, line);
128 line = line_stream_next(line_stream);