Skip to content

Instantly share code, notes, and snippets.

@gabtoschi
Created September 20, 2020 22:40
Show Gist options
  • Save gabtoschi/1bd1e1d6f1dba18eae5ccc81d0e8b9b9 to your computer and use it in GitHub Desktop.
Save gabtoschi/1bd1e1d6f1dba18eae5ccc81d0e8b9b9 to your computer and use it in GitHub Desktop.
C function to read a string to a heap array (I know that isn't the most optimized way to do this, but someone can make do with)
// stream: if you want to read from the standard input, use stdin
// delim: a delimiter to the function stop reading, you can use '\n' to a standard linebreak
char *readString(FILE *stream, char delim){
char *str = NULL;
int counter = 0;
char c;
do {
c = fgetc(stream);
str = realloc(str, sizeof(char)*(counter+1));
str[counter++] = c;
} while (c != delim && c != EOF);
str[--counter] = '\0';
return str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment