0

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.

5
  • 1
    while (!feof(pipe)) is wrong. Make it while(fgets(buffer, sizeof buffer, pipe) != nullptr) result += buffer; Commented Jan 1, 2024 at 16:04
  • 1
    It won't retain the context but it will also not do the unnecessary feof check. To keep the context, you could start a shell in a process and write to it via it's stdin and read its stdout. Commented Jan 1, 2024 at 16:06
  • I, understand, but how could one do that? Sorry for being inexperienced... Commented Jan 1, 2024 at 16:10
  • I would use boost::process. It makes it work as portably as possible afaik. Commented Jan 1, 2024 at 16:15
  • start cmd with redirected output and write commands via pipe when need. finally write exit\r\n command - stackoverflow.com/questions/77736860/… Commented Jan 1, 2024 at 17:27

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.