ohmu
·
2026-10-15
1#include "getline.h"
2
3#include <stdlib.h>
4#include <errno.h>
5
6ssize_t getline(char** lineptr, size_t* n, FILE* stream) {
7 ssize_t pos = -1;
8 int c;
9
10 if (lineptr == nullptr || stream == nullptr || n == nullptr) {
11 errno = EINVAL;
12 return -1;
13 }
14
15 _lock_file(stream);
16
17 c = _getc_nolock(stream);
18 if (c == EOF) {
19 goto exit;
20 }
21
22 if (*lineptr == nullptr) {
23 *lineptr = malloc(128);
24 if (*lineptr == nullptr) {
25 goto exit;
26 }
27 *n = 128;
28 }
29
30 pos = 0;
31 while (c != EOF) {
32 if ((size_t) (pos + 1) >= *n) {
33 size_t new_size = *n + (*n >> 2);
34 if (new_size < 128) {
35 new_size = 128;
36 }
37 char* new_ptr = realloc(*lineptr, new_size);
38 if (new_ptr == nullptr) {
39 pos = -1;
40 goto exit;
41 }
42 *n = new_size;
43 *lineptr = new_ptr;
44 }
45
46 ((char*) (*lineptr))[pos++] = (char) c;
47 if (c == '\n') {
48 break;
49 }
50 c = _getc_nolock(stream);
51 }
52
53 (*lineptr)[pos] = '\0';
54
55exit:
56 _unlock_file(stream);
57 return pos;
58}