I wanted to make a function that will dynamically retrieve a line from a stream to a buffer. This function just needs to take in the char*
and the stream to read from. It'll keep allocating a bigger buffer until it can read all the data into the rtr
variable (terminated on new line). Any ways I can improve this would be amazing.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
char* dynamic_fgets(char** rtr, FILE* stream) {
int bufsize = 1024; //Start at 1024 bytes
char* buf = (char*) malloc(bufsize*sizeof(char));
if(buf == NULL) {
perror("Couldn't allocate memory for buf in dynamic_fgets\n");
}
do {
fgets(buf, bufsize, stream);
*rtr = realloc(*rtr, strlen(buf)+strlen(*rtr));
if(*rtr == NULL) {
perror("Couldn't allocate memory for *rtr in dynamic_fgets\n");
}
*rtr = strncat(*rtr, buf, bufsize);
bufsize *= 2;
} while(buf[strlen(buf)-1] != '\n');
return *rtr;
}
int main(int argc, char** argv) {
char* buf = (char*) malloc(sizeof(1));
strncpy(buf, "\0", 1);
printf("Input: ");
dynamic_fgets(&buf, stdin);
printf("Output: %s", buf);
return 0;
}