I've looked everywhere for an answer to my question, but I have yet to find a solid answer to my problem.
I'm currently in the process of writing a program in C, specifically targeting the UNIX command line (I'm using Linux as my development environment, but I'd like for this program to be as portable as possible). Right now, I have a basic shell that prompts for user input. The user will then enter in a command, and that command will be processed accordingly. Here is the code that I have so far:
/* Main.c */
int main(int argc, char **argv)
{
while (TRUE)
{
display_prompt();
get_command();
}
return 0;
}
/* Main.h */
void get_command()
{
/*
* Reads in a command from the user, outputting the correct response
*/
int buffer_size = 20;
char *command = (char*) malloc(sizeof(char) * buffer_size);
if (command == NULL)
{
return_error("Error allocating memory");
}
fgets(command, buffer_size, stdin);
if (command[strlen(command) - 1] == '\n')
{
puts("It's inside the buffer.");
}
else
{
puts("It's not inside the buffer.");
}
free(command);
}
My initial thought was to check for the \n
character and see if it fit within the buffer_size
, and if it didn't realloc()
the data to expand the allocated memory.
However, after I realloc()
my string, how would I go about adding the remaining data from stdin
into command
?