Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read from stdin with fgets()?

Tags:

c

stdin

fgets

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; } 
like image 777
robdavies35 Avatar asked Oct 12 '10 21:10

robdavies35


People also ask

Can you use fgets on Stdin?

The function fgets() reads the characters till the given number from STDIN stream.

How does fgets () read the data from a file?

The fgets() function reads characters from the current stream position up to and including the first new-line character (\n), up to the end of the stream, or until the number of characters read is equal to n -1, whichever comes first.

How use fgets function?

C library function - fgets() The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

What is the difference between gets () and fgets ()?

Even though both the functions, gets() and fgets() can be used for reading string inputs. The biggest difference between the two is the fact that the latter allows the user to specify the buffer size. Hence it is highly recommended over the gets() function.


2 Answers

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; } 
like image 185
user411313 Avatar answered Sep 19 '22 20:09

user411313


You have a wrong idea of what fgets returns. Take a look at this: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

It returns null when it finds an EOF character. Try running the program above and pressing CTRL+D (or whatever combination is your EOF character), and the loop will exit succesfully.

How do you want to detect the end of the input? Newline? Dot (you said sentence xD)?

like image 32
slezica Avatar answered Sep 20 '22 20:09

slezica