Skip to content

Instantly share code, notes, and snippets.

@Yepoleb
Created February 13, 2019 23:01
Show Gist options
  • Save Yepoleb/95bcc4718dd5ef577594b4bcff0b0818 to your computer and use it in GitHub Desktop.
Save Yepoleb/95bcc4718dd5ef577594b4bcff0b0818 to your computer and use it in GitHub Desktop.
#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
const size_t BUFFERGROWTH = 128;
size_t getline_(char **lineptr, size_t *linesize, FILE *stream)
{
if (*lineptr == NULL) {
*lineptr = malloc(BUFFERGROWTH);
*linesize = BUFFERGROWTH;
}
size_t buffer_i = 0;
char c = 0;
while (c != '\n') {
// Detect need for buffer growth
if (buffer_i >= *linesize) {
*linesize += BUFFERGROWTH;
*lineptr = realloc(*lineptr, *linesize);
}
c = getc(stream);
if (c == -1) { // EOF
break;
}
(*lineptr)[buffer_i++] = c;
}
(*lineptr)[buffer_i] = '\0';
return buffer_i;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment