]> git.lizzy.rs Git - getline.git/blob - getline.c
Add CMake config
[getline.git] / getline.c
1 /* The original code is public domain -- Will Hartung 4/9/09 */
2 /* Modifications, public domain as well, by Antti Haapala, 11/10/17
3    - Switched to getc on 5/23/19 */
4 /* Modifications, public domain, by Elias Fleckenstein 24/04/2022 */
5
6 #include <stdlib.h>
7 #include <errno.h>
8 #include "getline.h"
9
10 ssize_t getline(char **lineptr, size_t *n, FILE *stream) {
11     size_t pos;
12     int c;
13
14     if (lineptr == NULL || stream == NULL || n == NULL) {
15         errno = EINVAL;
16         return -1;
17     }
18
19     c = getc(stream);
20     if (c == EOF) {
21         return -1;
22     }
23
24     if (*lineptr == NULL) {
25         *lineptr = malloc(128);
26         if (*lineptr == NULL) {
27             return -1;
28         }
29         *n = 128;
30     }
31
32     pos = 0;
33     while(c != EOF) {
34         if (pos + 1 >= *n) {
35             size_t new_size = *n + (*n >> 2);
36             if (new_size < 128) {
37                 new_size = 128;
38             }
39             char *new_ptr = realloc(*lineptr, new_size);
40             if (new_ptr == NULL) {
41                 return -1;
42             }
43             *n = new_size;
44             *lineptr = new_ptr;
45         }
46
47         ((unsigned char *)(*lineptr))[pos ++] = c;
48         if (c == '\n') {
49             break;
50         }
51         c = getc(stream);
52     }
53
54     (*lineptr)[pos] = '\0';
55     return pos;
56 }