如果您想要一种简洁且可移植的方式来访问文件和目录,那么请查看Boost.Filesystem.您应浏览文档以准确找到所需内容.下面是关于如何使用框架来完成任务的建议.
#include <iostream>
#include <filesystem>
using std::tr2::sys;
using std::cout;
void do_something_with_file( std::string const& p )
{
std::cout << "Found file : " << p << std::end;
}
void explore_directory( std::string const& p )
{
for (directory_iterator itr(p); itr!=directory_iterator(); ++itr)
{
if( is_directory(itr->status()) )
{
explore_directory(itr->path().filename());
}
else if( is_regular_file(itr->status()) )
{
do_something_with_file(itr->path().filename());
}
}
}
int main(int argc, char* argv[])
{
std::string p(argc <= 1 ? "." : argv[1]);
if (is_directory(p))
{
explore_directory(p);
}
else cout << (exists(p) : "Found: " : "Not found: ") << p << '\n';
return 0;
}
Run Code Online (Sandbox Code Playgroud)
小智 6
C++标准没有指定任何目录函数,因此您必须使用特定于实现的内容.例如,在Windows上,您可以使用该chdir()功能.声明<direct.h>.
顺便说一句,请注意,在发布此类问题时,请指出您感兴趣的操作系统.