implement pipe_to_string() and use it to shorten the test case sourcecode
[libi2ncommon] / src / pipestream.hxx
index 1fca37e..734b99c 100644 (file)
@@ -122,6 +122,42 @@ public:
     { buf.store_exit_status(_status_set, _exit_status); }
 };
 
+/** @brief runs command and returns it's output as string
+ *  @param command the full command with all parameters
+ *  @param exit_status the full exit status, use WEXITSTATUS to get the "regular" return code
+ *  @returns the output (stderr) of the called program
+ */
+std::string pipe_to_string(const std::string& command, std::string *error=NULL, int *_exit_status=NULL)
+{
+    std::string result;
+    bool exit_set;
+
+    try
+    {
+        inpipestream ips(command);
+
+        ips.store_exit_status(&exit_set, _exit_status);
+
+        char buffer[2048];
+        while (ips.good())
+        {
+            ips.read(buffer, sizeof(buffer));
+            result.append(buffer, ips.gcount());
+        }
+    }
+    catch (pipestream_error &e)
+    {
+        if (error)
+            *error=e.what();
+        return "";
+    }
+    catch(...)
+    {
+        throw;
+    }
+
+    return result;
+}
 
 /** @brief runs command and provides buffered ouptput from it through pipe
  *