Skip to content

Instantly share code, notes, and snippets.

@yeban
Created March 2, 2010 16:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save yeban/319653 to your computer and use it in GitHub Desktop.
Save yeban/319653 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment