Skip to content

Instantly share code, notes, and snippets.

@mrWeiss0
Created June 4, 2020 14:05
Show Gist options
  • Save mrWeiss0/5f7610b2808ee27b60f6ed1844f7755b to your computer and use it in GitHub Desktop.
Save mrWeiss0/5f7610b2808ee27b60f6ed1844f7755b to your computer and use it in GitHub Desktop.
readline function with increasing buffer
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#define LBUF_SZ 0x402
#define NEWL '\n'
struct string{
char *str;
size_t len;
};
struct string readline(FILE* stream){
char buf[LBUF_SZ];
struct string line = {NULL, 0};
int nl = 0;
while(!feof(stream)){
if(!fgets(buf, sizeof(buf), stream))
break;
size_t bufl = strlen(buf);
if(buf[bufl - 1] == NEWL){
nl = 1;
buf[--bufl] = '\0';
}
char *linet = realloc(line.str, line.len + bufl + 1);
if(!linet)
break;
line.str = linet;
strcpy(line.str + line.len, buf);
line.len += bufl;
if(nl)
break;
}
return line;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment