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