How to read from stdin with fgets()?

robdavies35 picture robdavies35 · Oct 12, 2010 · Viewed 209.2k times · Source

I've written the following code to read a line from a terminal window, the problem is the code gets stuck in an infinite loop. The line/sentence is of undefined length, therefore I plan to read it in parts into the buffer, then concatenate it to another string which can be extended via realloc accordingly. Please can somebody spot my mistake or suggest a better way of achieving this?

#include <stdio.h>
#include <string.h>

#define BUFFERSIZE 10

int main (int argc, char *argv[])
{
    char buffer[BUFFERSIZE];
    printf("Enter a message: \n");
    while(fgets(buffer, BUFFERSIZE , stdin) != NULL)
    {
        printf("%s\n", buffer);
    }
    return 0;
}

Answer

user411313 picture user411313 · Oct 12, 2010

here a concatenation solution:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFERSIZE 10

int main() {
  char *text = calloc(1,1), buffer[BUFFERSIZE];
  printf("Enter a message: \n");
  while( fgets(buffer, BUFFERSIZE , stdin) ) /* break with ^D or ^Z */
  {
    text = realloc( text, strlen(text)+1+strlen(buffer) );
    if( !text ) ... /* error handling */
    strcat( text, buffer ); /* note a '\n' is appended here everytime */
    printf("%s\n", buffer);
  }
  printf("\ntext:\n%s",text);
  return 0;
}