我正在编写一个需要打开另一个进程并获取其输出的应用程序。我在网上看到的所有地方都说我必须使用 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
中,结果是一个空字符串。我在终端中清楚地看到命令的输出。如果命令正常退出,则行为符合预期。但我只捕获错误情况的输出。
最佳答案
Popen 不捕获 stderr,只捕获 stdout。将 stderr 重定向到 stdout 可以解决这个问题。
#include <string>
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <array>
int main()
{
std::string command("ls afskfksakfafkas 2>&1");
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;
}
关于c++ - popen() 将执行命令的输出写入 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44610978/