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

19 lines
518 B
C++
Raw Permalink Normal View History

2023-07-01 11:58:00 -04:00
#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';
}