One of the easiest way is to use getline()
. The man
page describes the function as below:
ssize_t getline(char **lineptr, size_t *n, FILE *stream);
getline()
reads an entire line from stream, storing the address of the buffer containing the text into *lineptr
. The buffer is null-terminated and includes the newline character, if one was found.
By the way, keep in mind this paragraph:
If *lineptr
is set to NULL and *n
is set 0 before the call, then getline()
will allocate a buffer for storing the line. This buffer should be freed by the user program even if getline() failed.
Below a working sample.
#include <stdio.h>
int main(int argc, char* argv)
{
char* l = NULL;
size_t n;
while (getline(&l,&n, stdin) != -1 )
{
printf("%s",l);
}
free(l); // don't forget to release the allocated memory
// mmh, yes, here it's not useful since the program
// ends.
}
This answer is inspired by this SO reply.