How to read a line from the console in C? How to read a line from the console in C? c c

How to read a line from the console in C?


You need dynamic memory management, and use the fgets function to read your line. However, there seems to be no way to see how many characters it read. So you use fgetc:

char * getline(void) {    char * line = malloc(100), * linep = line;    size_t lenmax = 100, len = lenmax;    int c;    if(line == NULL)        return NULL;    for(;;) {        c = fgetc(stdin);        if(c == EOF)            break;        if(--len == 0) {            len = lenmax;            char * linen = realloc(linep, lenmax *= 2);            if(linen == NULL) {                free(linep);                return NULL;            }            line = linen + (line - linep);            linep = linen;        }        if((*line++ = c) == '\n')            break;    }    *line = '\0';    return linep;}

Note: Never use gets ! It does not do bounds checking and can overflow your buffer


If you are using the GNU C library or another POSIX-compliant library, you can use getline() and pass stdin to it for the file stream.


A very simple but unsafe implementation to read line for static allocation:

char line[1024];scanf("%[^\n]", line);

A safer implementation, without the possibility of buffer overflow, but with the possibility of not reading the whole line, is:

char line[1024];scanf("%1023[^\n]", line);

Not the 'difference by one' between the length specified declaring the variable and the length specified in the format string. It is a historical artefact.