2009-06-01 97 views
2

假設我想寫ls或dir。我如何獲得給定目錄中的文件列表? NET的Directory.GetFiles和其他信息。如何從C++文件夾中獲取文件名

不知道的字符串語法,但:

string[] filePaths = Directory.GetFiles(@"c:\MyDir\"); 
+2

重複:http://stackoverflow.com/questions/612097/how-can-i-get-a-list-of-files -in-a-directory-using-c-or-c – ChrisN 2009-06-01 15:19:02

+0

同意 - 如果SO允許,我會關閉 – MSalters 2009-06-02 13:01:45

回答

23

退房boost::filesystem,一個便攜和出色的圖書館。

編輯:從庫中的一個例子:

int main(int argc, char* argv[]) 
{ 
    std::string p(argc <= 1 ? "." : argv[1]); 

    if (is_directory(p)) 
    { 
    for (directory_iterator itr(p); itr!=directory_iterator(); ++itr) 
    { 
     cout << itr->path().filename() << ' '; // display filename only 
     if (is_regular_file(itr->status())) cout << " [" << file_size(itr->path()) << ']'; 
     cout << '\n'; 
     } 
    } 
    else cout << (exists(p) : "Found: " : "Not found: ") << p << '\n'; 

    return 0; 
} 
+0

+1:可移植的C++代碼。 – 2009-06-01 15:18:22

-3

這完全是平臺depeanded。
如果在Windows上,您應該按照建議使用WINAPI。

1

在Windows中: FindFirstFileFindNextFileFindClose可用於列出指定目錄中的文件。

僞代碼:

Find the first file in the directory. 
do 
    { 
    // 

    }while(NextFile); 

Close 
相關問題