3

bashコマンドの出力を文字列のベクトルに1行ずつ読み取る必要があります。このコードを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

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];
}
于 2012-08-19T15:05:09.900 に答える
1

C++ iostream 機能で CI/O を使用することはできません。本当に を使用したい場合は、 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 に答える