Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute a command and get output: popen and pclose undefined

As explained in this answer, I tried to execute a windows command and get the output within C++ in a visual studio project.

std::string executeCommand (const char* cmd) {
    char buffer[128];
    std::string result = "";
    std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);
    if (!pipe) throw std::runtime_error("popen() failed!");

    while (!feof(pipe.get())) {
        if (fgets(buffer, 128, pipe.get()) != NULL)
            result += buffer;
    }
    return result;
}

Problem is, this is not compiling.The following errors are given:

Error: identifier "popen" is undefined.
Error: identifier "pclose" is undefined.
like image 669
Kurt Van den Branden Avatar asked Mar 12 '23 11:03

Kurt Van den Branden


1 Answers

Since a Microsoft compiler is used, an underscore is needed at the beginning of popen and pclose. Replace:

std::shared_ptr<FILE> pipe(popen(cmd, "r"), pclose);

with:

std::shared_ptr<FILE> pipe(_popen(cmd, "r"), _pclose);
like image 144
Kurt Van den Branden Avatar answered Apr 26 '23 04:04

Kurt Van den Branden