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;
}
4

2 回答 2

1

I think you would like to use GNU library function 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];
}
于 2012-08-19T15:05:09.900 回答
1

您不能将 CI/O 与 C++ iostream 工具一起使用。如果你真的想使用,你需要通过readpopen来访问它的结果。

如果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;
}
于 2012-08-17T12:14:07.713 回答