Created
March 2, 2010 16:42
-
-
Save yeban/319653 to your computer and use it in GitHub Desktop.
A c function to take a string input of arbitrary length.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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