patterncppMinor
Running a shell command and getting output
Viewed 0 times
gettingoutputshellrunningandcommand
Problem
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:
Example use:
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::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?
Solution
Prefer comparing pointers to
nullptr instead of to NULL in C++11. nullptr exists for exactly that reason. The NULL macro is not portable. While it exists in many different environments there is no guarantee how it will be implemented or what it is intended to be used for. It may be implemented as 0, '\0', or as some pointer type, or anything else, and every different environment may define it differently or not at all. It is non-standard. nullptr is defined by the standard and all C++11 standard compliant compilers must support it.Context
StackExchange Code Review Q#42148, answer score: 5
Revisions (0)
No revisions yet.