Skip to content

Instantly share code, notes, and snippets.

@zambony
Last active March 1, 2020 22:14
Show Gist options
  • Save zambony/129ec81c6f20a4f1c64257381569859a to your computer and use it in GitHub Desktop.
Save zambony/129ec81c6f20a4f1c64257381569859a to your computer and use it in GitHub Desktop.
Custom function to accept input of unknown length from a user. Can change the max size the buffer can grow to.
#define CHUNK_SIZE 256
#define MAX_CHUNKS 4
/**
* Homemade readline. Dynamically read input.
*
* @param prompt The text to prefix the user's input with
* @param line Assigned the value of the user's input if not NULL
*
* @return The size of the read input
*/
ssize_t readline(const char *prompt, char **line)
{
if (prompt)
{
fputs(prompt, stdout);
}
*line = (char *) malloc(CHUNK_SIZE);
size_t bufSize = CHUNK_SIZE;
char read;
ssize_t pos = 0;
while ((read = getchar()) != '\n' && bufSize < (CHUNK_SIZE * MAX_CHUNKS))
{
if ((int) read == EOF)
{
errno = 0;
return -1;
}
(*line)[pos++] = read;
if (pos == bufSize)
{
bufSize += CHUNK_SIZE; // grow our buffer with extra padding in case
*line = realloc(*line, bufSize);
}
}
if (pos > 0)
{
// Shrink, but make room for \0
*line = realloc(*line, (pos + 1));
// dont forget to TERMINATE
(*line)[pos] = '\0';
}
return pos;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment