So I have this code that executes a system command and returns the output.
std::string ExecCmd(std::string command) {
char buffer[128];
std::string result = "";
FILE* pipe = _popen(command.c_str(), "r");
if (!pipe) {
return "popen failed!";
}
while (!feof(pipe)) {
if (fgets(buffer, 128, pipe) != NULL)
result += buffer;
}
_pclose(pipe);
return result;
}
This code works really well, except for one part: Everytime this function is executed the command is executed in a seperate subprocess, so I do not have "context", which I really need. Example:
std::cout << Control::ExecCmd("cd myfolder");
std::cout << Control::ExecCmd("cd");
this prints C:\Users\spata\Desktop\, not C:\Users\spata\Desktop\myfolder which it is supposed to. How do I make it so that I can execute commands in the same "context", while being able to retrieve the output? Keep in mind I cant just merge all the commands into one, they need to be executed separately, but in the same context. Happy new year everyone!
I tried to tinker with batch files, however that still didnt work, and batch files are inconvenient.
while (!feof(pipe))is wrong. Make itwhile(fgets(buffer, sizeof buffer, pipe) != nullptr) result += buffer;feofcheck. To keep the context, you could start a shell in a process and write to it via it's stdin and read its stdout.exit\r\ncommand - stackoverflow.com/questions/77736860/…