0

How to run a cmd command, and getting the output to a string variable? Example:

string result = ExecuteFunction("ipconfig");

Now "result" contains:

Windows IP Configuration
Ethernet adapter Local Area Connection:
Connection-specific DNS Suffix  . :
......

This shuld be happening without showing any cmd screen, all from the program. Windows platform of course.

user2216190
  • 784
  • 5
  • 10
  • 25

2 Answers2

1

You can build a pipe:

On Linux:

#include <cstdio>
#include <iostream>
#include <vector>

int main() {
    FILE* fp = popen("ifconfig", "r");
    if(fp) {
        std::vector<char> buffer(4096);
        std::size_t n = fread(buffer.data(), 1, buffer.size(), fp);
        if(n && n < buffer.size()) {
            buffer.data()[n] = 0;
            std::cout << buffer.data() << '\n';
        }
        pclose(fp);
    }
}

For Windows you might use '_popen' and change 'ifconfig' to 'ipconfig'

0

The standard solution for this problem since time immemorial is to use command line redirection to send standard output to a text file, and then read the file into a string.

You didn't provide enough context to respond with code. In C/C++ you could use _popen(). In .NET this answer might help. Redirect console output to textbox in separate program

Community
  • 1
  • 1
david.pfx
  • 10,520
  • 3
  • 30
  • 63
  • Hardly the standard solution. The standard solution would be to send standard output to a pipe and read that. No need to hit the file system. – David Heffernan Feb 01 '14 at 15:18
  • No, that solution only applies down the Unix/C branch of history. In the MSDOS/Windows 3/VB/Access branch pipes were not available, but command line redirection was. I guess this is the problem with answering questions that don't provide enough context. – david.pfx Feb 02 '14 at 00:43