crawlserv++  [under development]
Application for crawling and analyzing textual content of websites.
System.hpp
Go to the documentation of this file.
1 /*
2  *
3  * ---
4  *
5  * Copyright (C) 2020 Anselm Schmidt (ans[ät]ohai.su)
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version in addition to the terms of any
11  * licences already herein identified.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <https://www.gnu.org/licenses/>.
20  *
21  * ---
22  *
23  * System.hpp
24  *
25  * Namespace for global system helper function.
26  *
27  * Created on: Apr 17, 2019
28  * Author: ans
29  */
30 
31 #include "../Helper/Portability/pipe.h"
32 
33 #include "../Main/Exception.hpp"
34 
35 #include <array> // std::array
36 #include <cstdio> // ::fgets, FILE, pclose, popen
37 #include <memory> // std::unique_ptr
38 #include <string> // std::string
39 
42 
45 
47  inline constexpr auto cmdBufferLength{128};
48 
50 
52 
64  inline std::string exec(const char* cmd) {
65  std::array<char, cmdBufferLength> buffer{};
66  std::string result;
67 
68  // NOLINTNEXTLINE(cert-env33-c)
69  std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
70 
71  if(!pipe) {
72  throw Main::Exception("popen() failed");
73  }
74 
75  while(::fgets(buffer.data(), buffer.size(), pipe.get()) != nullptr) {
76  result += buffer.data();
77  }
78 
79  return result;
80  }
81 
82 } /* namespace crawlservpp::Helper::System */
std::string exec(const char *cmd)
Executes a system command and returns the stdout of the program.
Definition: System.hpp:64
Base class for all exceptions thrown by the application.
Definition: Exception.hpp:90
constexpr auto cmdBufferLength
The length of the buffer for executing system commands.
Definition: System.hpp:47
Namespace for global system helper functions.
Definition: System.hpp:41