56 lines
1.3 KiB
C
56 lines
1.3 KiB
C
// getline() is written to POSIX spec so that it can be used on Windows platforms
|
|
// This is taken from a stackexchange answer, link has since been lost.
|
|
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <stdint.h>
|
|
#include <errno.h>
|
|
|
|
typedef intptr_t ssize_t;
|
|
|
|
ssize_t getline(char** lineptr, size_t* n, FILE* stream) {
|
|
size_t pos;
|
|
int c;
|
|
|
|
if (lineptr == NULL || stream == NULL || n == NULL) {
|
|
errno = EINVAL;
|
|
return -1;
|
|
}
|
|
|
|
c = getc(stream);
|
|
if (c == EOF) {
|
|
return -1;
|
|
}
|
|
|
|
if (*lineptr == NULL) {
|
|
*lineptr = (char*)malloc(128);
|
|
if (*lineptr == NULL) {
|
|
return -1;
|
|
}
|
|
*n = 128;
|
|
}
|
|
|
|
pos = 0;
|
|
while (c != EOF) {
|
|
if (pos + 1 >= *n) {
|
|
size_t new_size = *n + (*n >> 2);
|
|
if (new_size < 128) {
|
|
new_size = 128;
|
|
}
|
|
char* new_ptr = (char*)realloc(*lineptr, new_size);
|
|
if (new_ptr == NULL) {
|
|
return -1;
|
|
}
|
|
*n = new_size;
|
|
*lineptr = new_ptr;
|
|
}
|
|
|
|
((unsigned char*)(*lineptr))[pos++] = c;
|
|
if (c == '\n') {
|
|
break;
|
|
}
|
|
c = getc(stream);
|
|
}
|
|
|
|
(*lineptr)[pos] = '\0';
|
|
return pos;
|
|
} |