#include <iostream>
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
usingnamespace std;
string cmdinput;
string GetStdoutFromCommand(string cmd) {
string data;
FILE * stream;
constint max_buffer = 256;
char buffer[max_buffer];
cmd.append(" 2>&1");
stream = popen(cmd.c_str(), "r");
if (stream) {
while (!feof(stream))
if (fgets(buffer, max_buffer, stream) != NULL) data.append(buffer);
pclose(stream);
}
return data;
}
int main (){
string com = GetStdoutFromCommand("apt-get install");
cout << "Command: " << com << endl;
return 0;
}
The program runs the entire shell command ("apt-get install") and prints output as it should:
1 2
Command: E: Could not open lock file /var/lib/dpkg/lock - open (13: Permission denied)
E: Unable to lock the administration directory (/var/lib/dpkg/), are you root?
However, when I replace ("apt-get install") with the string cmdinput (Declared on line 7) and revise the bottom section like so:
1 2 3 4 5 6 7
int main (){
cin >> cmdinput;
string com = GetStdoutFromCommand(cmdinput);
cout << "Command: " << com << endl;
return 0;
}
This allows me to input the command of which will executed... Sadly, it doesn't work very well. In contrast to example one, which had "apt-get install" coded into the program, having the user input "apt-get install" as per example two doesn't bring the correct result- it brings up the display that appears when you input just "apt" into the terminal...
So replacing "apt-get install" in example one with a string only allows the program to execute the first word in the string- why...? How can I fix this? I've been racking my brain for quite a while and nothing's come out...
EDIT: It is now apparent to be that it takes every different word from input as a seperate command- how can I make it take each word as one command- I.E. "apt-get install" instead of "apt-get" "install"?