diff options
Diffstat (limited to 'common/readline.c')
-rw-r--r-- | common/readline.c | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/common/readline.c b/common/readline.c new file mode 100644 index 00000000..e75b183f --- /dev/null +++ b/common/readline.c | |||
@@ -0,0 +1,39 @@ | |||
1 | #include "readline.h" | ||
2 | #include <stdlib.h> | ||
3 | #include <stdio.h> | ||
4 | |||
5 | char *read_line(FILE *file) { | ||
6 | int length = 0, size = 128; | ||
7 | char *string = malloc(size); | ||
8 | if (!string) { | ||
9 | return NULL; | ||
10 | } | ||
11 | while (1) { | ||
12 | int c = getc(file); | ||
13 | if (c == EOF || c == '\n' || c == '\0') { | ||
14 | break; | ||
15 | } | ||
16 | if (c == '\r') { | ||
17 | continue; | ||
18 | } | ||
19 | if (length == size) { | ||
20 | char *new_string = realloc(string, size *= 2); | ||
21 | if (!new_string) { | ||
22 | free(string); | ||
23 | return NULL; | ||
24 | } | ||
25 | string = new_string; | ||
26 | } | ||
27 | string[length++] = c; | ||
28 | } | ||
29 | if (length + 1 == size) { | ||
30 | char *new_string = realloc(string, length + 1); | ||
31 | if (!new_string) { | ||
32 | free(string); | ||
33 | return NULL; | ||
34 | } | ||
35 | string = new_string; | ||
36 | } | ||
37 | string[length] = '\0'; | ||
38 | return string; | ||
39 | } | ||