yeban
3/2/2010 - 4:42 PM

A c function to take a string input of arbitrary length.

A c function to take a string input of arbitrary length.

//the return pointer must be freed
char* readline() {

    char buffer;
    char *command = NULL;
    char *tmp = NULL;
    int size = 0;
    int last = 0;

    while ( 1 ){ //listen indefinitely for characters

	//the size of buffer required to hold the command( grows dynamically )
	size = size + sizeof( char );

	//allocate space for the new character
	tmp = realloc( command, size );

	if( tmp == NULL  ){//realloc failed
	    free( command );
	    return NULL;
	}
	else{ //get and store the character
	    command = tmp;
	    if( ( buffer = getchar() ) != '\n' )
		command[ last++ ] = buffer;
	    else break; //break if carriage return is entered
	}
    }

    //a string is always null terminated
    command[ last ] = '\0';

    return command;
}