RosettaCodeData/Task/Get-system-command-output/C++/get-system-command-output-1...

19 lines
518 B
C++

#include <fstream>
#include <iostream>
std::string execute(const std::string& command) {
system((command + " > temp.txt").c_str());
std::ifstream ifs("temp.txt");
std::string ret{ std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>() };
ifs.close(); // must close the inout stream so the file can be cleaned up
if (std::remove("temp.txt") != 0) {
perror("Error deleting temporary file");
}
return ret;
}
int main() {
std::cout << execute("whoami") << '\n';
}