2012-08-17 152 views
2

我需要一個bash命令的輸出讀入由line.I串線的矢量嘗試這種代碼與ifstream的載體,但它給錯誤。我必須用什麼來解析它們而不是ifstream?逐行讀取命令行的輸出轉換成字符串的在C++中

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 2012-08-17 12:10:15

+0

@pmr Boost Filesystem與管道有什麼關係? – 2012-08-17 12:40:07

+0

「它給錯誤」不是一個很好的問題描述。這是編譯時錯誤嗎?運行時錯誤?是否有一些特定的錯誤信息?或者你的行爲與你期望的不同? – 2012-08-17 12:41:49

回答

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

我想你想使用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]; 
}