Skip to content

Instantly share code, notes, and snippets.

@alsamitech
Last active May 22, 2021 19:12
Show Gist options
  • Save alsamitech/e6cca60f2c1a33a2cdafea0416eb2406 to your computer and use it in GitHub Desktop.
Save alsamitech/e6cca60f2c1a33a2cdafea0416eb2406 to your computer and use it in GitHub Desktop.
getline - Gets a line from a stream
char* getline(FILE* stream){
size_t bytes=0;
unsigned int capacity=64;
char* buf=malloc(capacity);
char c;
#ifdef __unix__
while((c=fgetc(stream))!=EOF&&c!='\n')
#else
while((c=fgetc(stream))!=EOF&&c!='\n'&&c!='\r')
#endif // __unix__
{
bytes++;
if(bytes+1>=capacity){
capacity*=2;
buf=realloc(buf, capacity);
if(!buf){
return 0x0;
}
}
buf[bytes-1]=c;
}
return buf;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment