在C ++中逐行读取命令行输出并将其存储为字符串向量

3
我需要逐行将bash命令的输出读入字符串向量中。我使用了ifstream来尝试这个代码,但出现了错误。我应该使用什么来代替ifstream解析它们?
using namespace std;

int main()
{
  vector<string> text_file;
  string cmd = "ls";

  FILE* stream=popen(cmd.c_str(), "r");
  ifstream ifs( stream );

  string temp;
  while(getline(ifs, temp))
     text_file.push_back(temp);
  for (int i=0; i<text_file.size(); i++)
      cout<<text_file[i]<<endl;
}

1
无法使用ifstream与C库文件流一起使用。您需要坚持使用C I/O,并可能将其结果转换为std::string。您**真正想要的是Boost.Filesystem。 - pmr
@pmr Boost Filesystem 和管道有什么关系? - James Kanze
“it gives error” 不是一个很好的问题描述。这是编译时错误吗?运行时错误?有特定的错误信息吗?还是你得到了与预期不同的结果? - David Schwartz
@JamesKanze 我假设ls实际上是他想要实现的,但我可能错了。抱歉。 - pmr
1
@pmr 哦,你可能是对的。我甚至没有看过实际的命令(因为标题谈到了捕获另一个程序输出的问题)。我同意:使用Boost Filesystem,而不是从ls管道传输。(对于其他命令:我曾经有一个"pipebuffer"类,其中包括"opipestream"和"ipipestream",但我不知道它们是否还存在。在我看来,那将是最好的方法。) - James Kanze
2个回答

1

你不能在C++的iostream设施中使用C I/O。如果你真的想使用popen,你需要用read访问它的结果。

如果ls确实是你想要做的事情,请尝试使用Boost.Filesystem

#include <boost/filesystem.hpp>
#include <vector>

int main()
{
  namespace bfs = boost::filesystem;
  bfs::directory_iterator it{bfs::path{"/tmp"}};
  for(bfs::directory_iterator it{bfs::path{"/tmp"}}; it != bfs::directory_iterator{}; ++it) { 
    std::cout << *it << std::endl;
  }

  return 0;
}

1

我认为您会喜欢使用GNU库函数getline

int main ()
{
    vector<string> text_file;
    FILE *stream = popen ("ls", "r");
    char *ptr = NULL;
    size_t len;
    string str;

    while (getline (&ptr, &len, stream) != -1)
    {
        str = ptr;
        text_file.push_back (str);
    }
    for (size_t i = 0; i < text_file.size(); ++i)
        cout << text_file[i];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接