I am running a system command from C++ which prints out some output to the terminal. I need to store this output in a file, therefore I am currently using the below function which returns the output in the result
variable (the code is from some other SO question which I cannot find right now):
std::string execWithSuccessCode(const std::string& cmd, int& exit_code) {
std::array<char, 128> buffer;
std::string result;
#if defined(__linux__)
auto pipe = popen(cmd.c_str(), "r"); // get rid of shared_ptr
#elif _WIN32
auto pipe = _popen(cmd.c_str(), "r"); // get rid of shared_ptr
#endif
if (!pipe) throw std::runtime_error("popen() failed!");
while (!feof(pipe)) {
if (fgets(buffer.data(), buffer.size(), pipe) != nullptr)
result += buffer.data();
}
#if defined(__linux__)
exit_code = pclose(pipe);
#elif _WIN32
exit_code = _pclose(pipe);
#endif
return result;
}
However, the command can take a long while (and even get stuck in which case it needs to be aborted), so I would also wish to see the output WHILE IT IS BEING PRODUCED, because it includes a progress bar.
Is it at all possible to simultaneously print the output into the terminal and in the end store it in a variable?