This is the code I'm currently using to run a shell command on the current machine, intended for use only with GNU/Linux at the moment:
std::string getCmdOutput(const std::string& mStr)
{
std::string result, file;
FILE* pipe{popen(mStr.c_str(), "r")};
char buffer[256];
while(fgets(buffer, sizeof(buffer), pipe) != NULL)
{
file = buffer;
result += file.substr(0, file.size() - 1);
}
pclose(pipe);
return result;
}
Example use:
getCmdOutput(R"( sudo pacman -Syyuu )");
auto output(getCmdOutput(R"( echo /etc/pacman.conf )"));
I use this when making simple script-like C++ programs (mostly for personal use).
Is this the "correct" way of doing it? What can be improved?
std::ifstream
to get the output of a shell command? I tried usingstd::getline
but I do not receive any output. \$\endgroup\$