blob: 202c7e222e4426ba9d9d9e3bed7095d97260a081 (
plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
|
#include "getline.h"
#include <stdlib.h>
#include <errno.h>
// MSVC specific implementation
static void fseterr(FILE *fp)
{
struct file { // Undocumented implementation detail
unsigned char *_ptr;
unsigned char *_base;
int _cnt;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
};
#define _IOERR 0x10
((struct file *)fp)->_flag |= _IOERR;
}
ssize_t getdelim(char **restrict lineptr, size_t *restrict n, int delim, FILE *restrict stream)
{
if (lineptr == NULL || n == NULL || stream == NULL || (*lineptr == NULL && *n != 0)) {
errno = EINVAL;
return -1;
}
if (feof(stream) || ferror(stream)) {
return -1;
}
if (*lineptr == NULL) {
*n = 256;
*lineptr = malloc(*n);
if (*lineptr == NULL) {
fseterr(stream);
errno = ENOMEM;
return -1;
}
}
ssize_t nread = 0;
int c = EOF;
while (c != delim) {
c = fgetc(stream);
if (c == EOF) {
break;
}
if (nread >= (ssize_t)(*n - 1)) {
size_t newn = *n * 2;
char *newptr = realloc(*lineptr, newn);
if (newptr == NULL) {
fseterr(stream);
errno = ENOMEM;
return -1;
}
*lineptr = newptr;
*n = newn;
}
(*lineptr)[nread++] = c;
}
if (c == EOF && nread == 0) {
return -1;
}
(*lineptr)[nread] = 0;
return nread;
}
ssize_t getline(char **restrict lineptr, size_t *restrict n, FILE *restrict stream)
{
return getdelim(lineptr, n, '\n', stream);
}
|