-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathShellExecVec.hpp
43 lines (36 loc) · 1.08 KB
/
ShellExecVec.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
#ifndef ASU_SHELLEXECVEC
#define ASU_SHELLEXECVEC
#include<string>
#include<array>
#include<memory>
#include<vector>
/*************************************************
* This C++ template returns the stdout from the
* execution of given shell command.
*
* input(s):
* const T &cmd ---- Input command. Most time T should be a string.
*
* return(s):
* vector<string> ans ---- stdout from the Shell command as vector of strings.
*
* Shule Yu
* Jan 17 2018
*
* Key words: Shell, standard output.
*************************************************/
std::vector<std::string> ShellExecVec(const std::string &cmd) {
std::vector<std::string> ans;
std::array<char,128> buffer;
std::shared_ptr<FILE> pipe(popen(cmd.c_str(), "r"), pclose);
if (!pipe) throw std::runtime_error("ShellExecVec popen() failed! Command is: "+cmd);
while (!feof(pipe.get())) {
if (fgets(buffer.data(), 128, pipe.get()) != NULL)
ans.push_back(std::string(buffer.data()));
}
for (auto &s:ans)
if (s.back()=='\n')
s.pop_back();
return ans;
}
#endif