Skip to content

Instantly share code, notes, and snippets.

@sant123
Forked from 1995eaton/readin.c
Last active June 17, 2020 02:08
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save sant123/c681cd0b1f1e9ad1c758b793e4b90d42 to your computer and use it in GitHub Desktop.
C stdin reader example with dynamic memory allocation
#include <stdio.h>
#include <stdlib.h>
static char *read_stdin(void)
{
size_t cap = 4096, /* Initial capacity for the char buffer */
len = 0; /* Current offset of the buffer */
char *buffer = malloc(cap * sizeof(char));
int c;
/* Read char by char, breaking if we reach EOF or a newline */
while ((c = fgetc(stdin)) != '\n' && !feof(stdin))
{
buffer[len] = c;
/* When cap == len, we need to resize the buffer
* so that we don't overwrite any bytes
*/
if (++len == cap)
{
/* Make the output buffer twice its current size */
buffer = realloc(buffer, (cap *= 2) * sizeof(char));
}
}
/* If EOF, clear stdin error for future readings */
if (c == EOF)
{
clearerr(stdin);
}
/* Trim off any unused bytes from the buffer */
buffer = realloc(buffer, (len + 1) * sizeof(char));
/* Pad the last byte so we don't overread the buffer in the future */
buffer[len] = '\0';
return buffer;
}
int main (void)
{
char *input = read_stdin();
printf("%s\n", input);
free(input); /* Don't forget to free the memory allocated with malloc */
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment