Skip to content

Instantly share code, notes, and snippets.

@ziap
Created October 14, 2024 07:59
Show Gist options
  • Save ziap/7283d052fd5388d8052869a800289b4f to your computer and use it in GitHub Desktop.
Save ziap/7283d052fd5388d8052869a800289b4f to your computer and use it in GitHub Desktop.
Read a line from stdin into a malloc'd buffer
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *read_line_malloc(void) {
size_t sz = 64;
char *buf = malloc(sz);
if (!fgets(buf, sz, stdin)) {
*buf = '\0';
return buf;
}
size_t len = strlen(buf);
while (buf[len - 1] != '\n') {
sz *= 2;
buf = realloc(buf, sz);
if (!fgets(buf + len, sz - len, stdin)) {
return buf;
}
len += strlen(buf + len);
}
buf[len - 1] = '\0';
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment