4

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.
Community
  • 1
  • 1
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85

1 Answers1

7

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);
Kurt Van den Branden
  • 11,995
  • 10
  • 76
  • 85