cpp execute command

Solutions on MaxInterview for cpp execute command by the best coders in the world

showing results for - "cpp execute command"
Alessandra
01 Jan 2020
1//----------------------------------
2//  CREDIT: gregpaton08 on stack overflow
3//  https://stackoverflow.com/questions/478898/how-do-i-execute-a-command-and-get-the-output-of-the-command-within-c-using-po
4//----------------------------------
5#include <cstdio>
6#include <iostream>
7#include <memory>
8#include <stdexcept>
9#include <string>
10#include <array>
11
12std::string exec(const char* cmd) {
13    std::array<char, 128> buffer;
14    std::string result;
15    std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
16    if (!pipe) {
17        throw std::runtime_error("popen() failed!");
18    }
19    while (fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
20        result += buffer.data();
21    }
22    return result;
23}
24
queries leading to this page
cpp execute commandcpp execute command