Fetching Text

Seeing the limitations of the C library input functions, I set out a long time ago to craft my own input function. It does exactly what I need, which is the charm of writing your own functions — and the beauty of the C language because it gives you access to the low-level tools that allow for such play.

Over the years, my input() function changed. The version you see below is rather basic: It reads the standard input stream and lops off the string when the input buffer is full or a newline is encountered.

#include <stdio.h>

int input(char *s,int length);

int main()
{
    char buffer[32];
    int characters;

    printf("Type something: ");
    characters = input(buffer,32);
    printf("%d characters were read.\n",characters);
    printf("You typed: '%s'\n",buffer);

    return(0);
}

int input(char *s,int length)
{
    char ch,*base;

    base = s;
    while(1)
    {
        if( s == base+length-1)
        {
            *s = '\0';
            break;
        }
        ch = getchar();
        if( ch == '\n')
        {
            *s = '\0';
            break;
        }
        *s = ch;
        s++;
    }

    return(s-base);
}

The input() function returns the number of characters read and stored. That return value is displayed by Line 11. The string input is barfed out at Line 13.

The input() function (Line 18) uses pointer s to represent the buffer where the characters are stored. A second pointer, base, saves the buffer’s starting location (Line 22).

An endless while loop, starting at Line 23, keeps reading characters and placing them into the buffer. The first stop condition is calculated at Line 25, to see whether the buffer is full. If so, the string is capped (Line 27) and the loop is broken. The base+length-1 calculation ensures that room is available for the null character.

The second termination condition is tested after a character is read (Line 30). If that character is a newline, then the if condition at Line 31 catches it, the string is capped (Line 33) and the loop is broken. The newline is not saved as part of the string.

Because this input() function uses standard input, and my computer’s terminal handles backspace and other control characters. In some variations of this function, I’ve had to code what happens when you type control characters, such as Backspace, Tab, and Ctrl+U (erase line).

Next Lesson I cover a new C Library text-input function, getline().