Skip to content

Instantly share code, notes, and snippets.

@Random832
Last active April 3, 2022 07:11
Show Gist options
  • Save Random832/709702cc0853c3231afb407866a41fff to your computer and use it in GitHub Desktop.
Save Random832/709702cc0853c3231afb407866a41fff to your computer and use it in GitHub Desktop.
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// comically small buffer to prove the recursion concept
#define BUF 16
static ssize_t innerget(char **lineptr, size_t *n, int delim, FILE *stream, size_t offset) {
char buf[BUF];
for(size_t i=0; i<BUF; i++) {
int c = getc(stream);
if(c != EOF)
buf[i] = c;
if(c == EOF || c == delim) {
*n = offset+i;
*lineptr = realloc(*lineptr, *n+1);
if(!*lineptr) return -1;
(*lineptr)[*n] = '\0';
memcpy(*lineptr+offset, buf, i);
if(c == EOF) return -1;
else return *n;
}
}
ssize_t r = innerget(lineptr, n, delim, stream, offset+BUF);
if(*lineptr) {
memcpy(*lineptr+offset, buf, BUF);
}
return r;
}
ssize_t getdelim(char **lineptr, size_t *n, int delim, FILE *stream) {
return innerget(lineptr, n, delim, stream, 0);
}
ssize_t getline(char **lineptr, size_t *n, FILE *stream) {
return getdelim(lineptr, n, '\n', stream);
}
int main() {
size_t n;
char *p = 0;
getline(&p, &n, stdin);
printf("got %zu '%s'\n", n, p);
free(p);
n=0; p=0;
getline(&p, &n, stdin);
printf("got %zu '%s'\n", n, p);
}
// extending the concept to asprintf is left as an exercise for the reader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment