reldb 0.1.0
Recreational SQLite
Loading...
Searching...
No Matches
inputbuffer.c
Go to the documentation of this file.
1
5
6#include "inputbuffer.h"
7
10{
11 InputBuffer *inbuffer = (InputBuffer *)malloc(sizeof(InputBuffer));
12 if (inbuffer == NULL) {
13 return NULL;
14 }
15
16 inbuffer->buffer = NULL;
17 inbuffer->buffer_length = 0;
18 inbuffer->input_length = 0;
19
20 return inbuffer;
21}
22
24getline(char **lineptr, size_t *n, FILE *stream)
25{
26 int c;
27 size_t pos = 0;
28
29 if (*lineptr == NULL) {
30 *n = 128;
31 *lineptr = malloc(*n);
32 if (*lineptr == NULL) {
33 return -1;
34 }
35 }
36
37 while ((c = fgetc(stream)) != EOF) {
38 if (pos + 1 >= *n) {
39 *n *= 2;
40 *lineptr = realloc(*lineptr, *n);
41 if (*lineptr == NULL) {
42 return -1;
43 }
44 }
45 (*lineptr)[pos++] = c;
46 if (c == '\n') {
47 break;
48 }
49 }
50 (*lineptr)[pos] = '\0';
51
52 return (c == EOF && pos == 0) ? -1 : (ssize_t)pos;
53}
54
55void
56read_input(InputBuffer *input_buffer)
57{
58 ssize_t bytes_read =
59 getline(&(input_buffer->buffer), &(input_buffer->buffer_length), stdin);
60
61 if (bytes_read <= 0) {
62 printf("Error reading input\n");
63 exit(EXIT_FAILURE);
64 }
65
66 // Ignore trailing newline
67 input_buffer->input_length = bytes_read - 1;
68 input_buffer->buffer[bytes_read - 1] = 0;
69}
70
71void
73{
74 free(input_buffer->buffer);
75 free(input_buffer);
76}
void close_input_buffer(InputBuffer *input_buffer)
Frees the memory associated with an InputBuffer.
Definition inputbuffer.c:72
InputBuffer * new_input_buffer(void)
Allocates and initializes a new InputBuffer.
Definition inputbuffer.c:9
ssize_t getline(char **lineptr, size_t *n, FILE *stream)
Reads an entire line from a stream into a dynamically resizing buffer.
Definition inputbuffer.c:24
void read_input(InputBuffer *input_buffer)
Reads a line of input from standard input into the buffer.
Definition inputbuffer.c:56
Defines the InputBuffer structure and related I/O functions.
ptrdiff_t ssize_t
Signed size type, typically used to represent lengths or -1 for errors.
Definition inputbuffer.h:18
A structure to hold dynamically allocated string input data.
Definition inputbuffer.h:24
ssize_t input_length
Definition inputbuffer.h:26
size_t buffer_length
Definition inputbuffer.h:25
char * buffer
Definition inputbuffer.h:27