1

Hello i was try to run execute windows command using _popen and its work fine in vc++ in console.

while same code i do in c++ builder vcl form popen return null pointer ?

vc++

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    FILE* pipe = _popen(cmd, "r");
    if (!pipe) throw std::runtime_error("popen() failed!");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    }
    catch (...) {
        _pclose(pipe);
        throw;
    }
    _pclose(pipe);
    return result;
}

c++ builder same as above

void __fastcall TForm2::btn_adb_readInfoClick(TObject *Sender) {
    const char* cmd = "D:\\adb\\adb.exe devices";
    char buffer[128];
    std::string result = "";
    FILE* pipe = _popen(cmd, "r"); // always null
    char* er = strerror(errno);
    try
    {
        if (!pipe) throw std::runtime_error("popen() failed!");
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    }
    catch (std::exception &ex) {
        _pclose(pipe);
        throw;
    }
    _pclose(pipe);
}
Starl1ght
  • 4,422
  • 1
  • 21
  • 49
user1965804
  • 111
  • 3
  • 11

1 Answers1

3

The MSDN documentation for _popen states:

If used in a Windows program, the _popen function returns an invalid file pointer that causes the program to stop responding indefinitely. _popen works properly in a console application.

I'm assuming that C++ Builder is creating a Windows application and not a Console application.

dalle
  • 18,057
  • 5
  • 57
  • 81