How to read from stdin with fgets()?

Viewed 252629

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;
}
6 Answers

Check the length of string that is read into the buffer each time, and use that to break out of the loop.

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

#define LEN 10

int main()
{
        char buffer[LEN];
        char *str = calloc(LEN,sizeof(char));
        short flag = 0;
        while(!flag && fgets(buffer, LEN, stdin))       
        {
                str = realloc(str, strlen(str)+strlen(buffer)+1);
                if(!str) exit(1);
                if(strlen(buffer) != LEN-1)
                        flag = 1;
                strcat(str,buffer);
        }
        printf("%s",str);
        return 0;
}
Related