我正在编写一个需要打开另一个进程并获取其输出的应用程序。我在网上到处阅读,我必须使用popen
并从文件中读取。
但我无法从中读到。命令的输出将输出到调用应用程序的控制台窗口中。以下是我正在使用的代码。我添加了一些打印件进行调试。
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <array>
int main()
{
// some command that fails to execute properly.
std::string command("ls afskfksakfafkas");
std::array<char, 128> buffer;
std::string result;
std::cout << "Opening reading pipe" << std::endl;
FILE* pipe = popen(command.c_str(), "r");
if (!pipe)
{
std::cerr << "Couldn't start command." << std::endl;
return 0;
}
while (fgets(buffer.data(), 128, pipe) != NULL) {
std::cout << "Reading..." << std::endl;
result += buffer.data();
}
auto returnCode = pclose(pipe);
std::cout << result << std::endl;
std::cout << returnCode << std::endl;
return 0;
}
读取永远不会打印到我的cout
,结果是一个空字符串。我清楚地看到终端中命令的输出。如果命令正常退出,则行为符合预期。但我只捕获错误情况的输出。
答案 0 :(得分:5)
Popen没有捕获stderr只有stdout。将stderr重定向到stdout可以解决问题。
$LeftSide = ($Diff | Where-Object {$_.SideIndicator -eq '<='}).InputObject
答案 1 :(得分:3)
你必须添加&#34; 2&gt;&amp; 1&#34;在命令字符串的末尾
command.append(" 2>&1");