Created
October 14, 2024 07:59
-
-
Save ziap/7283d052fd5388d8052869a800289b4f to your computer and use it in GitHub Desktop.
Read a line from stdin into a malloc'd buffer
This file contains hidden or 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
#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