Created
May 22, 2018 17:35
-
-
Save OlivierLDff/145220e21125da08f787b2b206c80b92 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
size_t getline(char **lineptr, size_t *n, FILE *stream) { | |
char *bufptr = nullptr; | |
size_t it = 0; | |
int c; | |
if (lineptr == nullptr) { | |
return -1; | |
} | |
if (stream == nullptr) { | |
return -1; | |
} | |
if (n == nullptr) { | |
return -1; | |
} | |
bufptr = *lineptr; | |
size_t size = *n; | |
c = fgetc(stream); | |
if (c == EOF) { | |
return -1; | |
} | |
if (bufptr == nullptr) { | |
bufptr = (char*)malloc(128); | |
if (bufptr == nullptr) { | |
return -1; | |
} | |
size = 128; | |
} | |
while (c != EOF) { | |
if (it >= size) | |
{ | |
size = size + 128; | |
bufptr = (char*)realloc(bufptr, size); | |
if (bufptr == nullptr) { | |
return -1; | |
} | |
} | |
bufptr[it++] = c; | |
if (c == '\n') | |
break; | |
c = fgetc(stream); | |
} | |
bufptr[it++] = '\0'; | |
*lineptr = bufptr; | |
*n = size; | |
return it - 1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment