How to read a line from the console in C

What is the simplest way to read a full line in a C console program The text entered might have a variable length and we can't make any assumption about its content.


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)

        if(--len == 0) {
            len = lenmax;
            char * linen = realloc(linep, lenmax *= 2);

            if(linen == NULL) {
                return NULL;
            line = linen + (line - linep);
            linep = linen;

        if((*line++ = c) == '\n')
    *line = '\0';
    return linep;

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

Need Your Help

check whether a textbox value changed in .net .net visual-studio-2010

I am using the following code to check whether the textbox value is changed. The text box value is initially retrieved from the database in a button click event.

Using javaScript variable to add css property?

javascript html css variables var

I need to be able to count on how high a HTML element(div) should be...