Question

I am writing a program and i decided for input/output it would be best to allow for custom commands. I have written a config file and defined a series of commands (just echo, etc) and call these within the program using system(). The problem is that i need to get input from these commands. I tried using "read ANSWER" and then getenv("ANSWER) but this returns a null string. What is the best method to do this?

Was it helpful?

Solution

Since you don't provide any code, I have to use my imagination. Let me know if I get it wrong. You are doing something like this:

system("command");

And, you want to be able to read the output that is generated by that command. If I am wrong, please provide the code you are using in your question.

If I am right, then, you want to use popen instead. It opens a C style I/O stream. You can specify either for reading or writing (but not both). You want to use "r" for reading. Close the stream with pclose when you are done.

char buf[512];
FILE *cmd = popen("command", "r");
while (fgets(buf, sizeof(buf), cmd) != 0) {
    //...
}
pclose(cmd);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top