2009-06-01 173 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 
相关问题