Created
June 4, 2020 14:05
-
-
Save mrWeiss0/5f7610b2808ee27b60f6ed1844f7755b to your computer and use it in GitHub Desktop.
readline function with increasing 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 <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