Search code examples
c++stringfileparsingpopen

Parse from FILE structure to string in C++


I'm trying to capture a system command on Windows with the following code, to return the output as a string.

std::string exec(char* cmd) {
    FILE* pipe = _popen(cmd, "r");
    if (!pipe) return "ERROR";
    std::ifstream ifs(pipe);
    std::string content( (std::istreambuf_iterator<char>(ifs) ),
                         (std::istreambuf_iterator<char>()    ) );
    printf("%s", content);
    return content;
}

When I call the function like this:

char *command = "set";
std::string results = exec(command);
printf("%s", results);
getchar();

The output is just a few random bytes.

    ╝÷:ö°:

I was trying to get all the results appended in 1 long string. Can anyone tell me what I'm doing wrong? I tried redirecting the stderr to output with the command but it also gives some random bytes.


Solution

  • Since you're using printf() which knows nothing about C++ std::string values, you need to print the C string representation of the content:

    printf("%s", content.c_str());
    

    The printf() function was told to expect that, but it wasn't what you passed to it.

    Or, as others pointed out, you should use the native C++ I/O:

    std::cout << content;