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.

1
  • Is the C++ tag correct? It looks more like C#. Context would help. Commented Feb 2, 2014 at 0:48

2 Answers 2

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'

Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

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.
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.