-
multiple commands
Hello everyone,
I am trying to make my program so that it can listen to multiple commands seperated by a character.
Lets say I have a simple program like this:
Code:
#include <stdio.h>
int main(void)
{
char buf[128];
printf("Please enter a command: ");
gets(buf);
if(!strcmp(buf, "command1")) puts("do something");
if(!strcmp(buf, "command2")) puts("do something else");
if(!strcmp(buf, "command3")) puts("....");
return 0;
}
How could I make it so that it would accept an input like: command1 | command3
I was thinking of using strchr, but how can I make it so that it compares to the buf, can anyone provide an example, that would be great.
Best regards,
apsync.
-
Hmm, I wrote something like this awhile ago, but I doubt you want it to reach the same amount of depth.
First of all, detecting the pipe character is as easy as you say: Use strchr() or whatever the function name is to find a character inside the string. Alternatively you could read character by character manually and find the pipe character that way. Regardless, if it's there, then you could break down the string into 2 different strings containing the two different commands.
As a warning, however, the pipe character on the command line signifies more than just running two commands at once. It is used to start two separate processes and "pipe" the output of the first program into the input of the second program. Basically, stdout of process 1 is connected to stdin of process 2. It doesn't sound like this is what you want to do with your program, so if not, you can ignore this paragraph. If it is what you want to do (ie. mimic the way your terminal behaves), it can get somewhat complicated.
Offtopic:
Do not read strings with gets(). Use fgets() instead.
http://faq.cprogramming.com/cgi-bin/...&id=1043284351
http://faq.cprogramming.com/cgi-bin/...&id=1043284385