您如何在标准 C 中递归地遍历每个文件/目录?

新手上路,请多包涵

如何在标准 C++ 中递归地遍历每个文件/目录?

原文由 robottobor 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 606
2 个回答

在标准 C++ 中,技术上没有办法做到这一点,因为标准 C++ 没有目录的概念。如果你想稍微扩展你的网络,你可能想看看使用 Boost.FileSystem 。这已被接受以包含在 TR2 中,因此这为您提供了使您的实现尽可能接近标准的最佳机会。

一个例子,直接取自网站:

 bool find_file( const path & dir_path,         // in this directory,
                const std::string & file_name, // search for this name,
                path & path_found )            // placing path here if found
{
  if ( !exists( dir_path ) ) return false;
  directory_iterator end_itr; // default construction yields past-the-end
  for ( directory_iterator itr( dir_path );
        itr != end_itr;
        ++itr )
  {
    if ( is_directory(itr->status()) )
    {
      if ( find_file( itr->path(), file_name, path_found ) ) return true;
    }
    else if ( itr->leaf() == file_name ) // see below
    {
      path_found = itr->path();
      return true;
    }
  }
  return false;
}

原文由 1800 INFORMATION 发布,翻译遵循 CC BY-SA 2.5 许可协议

员工 Visual C++ 和 WIN API:

 bool Parser::queryDIR(string dir_name) {
    vector<string> sameLayerFiles;
    bool ret = false;
    string dir = "";
    //employee wide char
    dir = dir_name  + "\\*.*";;
    //employee WIN File API
    WIN32_FIND_DATA  fd;
    WIN32_FIND_DATA  fd_dir;
    HANDLE hFind = ::FindFirstFile(getWC(dir.c_str()), &fd);
    HANDLE hFind_dir = ::FindFirstFile(getWC(dir.c_str()), &fd_dir);
    string str_subdir;
    string str_tmp;
    //recursive call for diving into sub-directories
    do {
        if ((fd_dir.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
            //ignore trival file node
            while(true) {
                FindNextFile(hFind_dir, &fd_dir);
                str_tmp = wc2str(fd_dir.cFileName);
                if (str_tmp.compare(".") && str_tmp.compare("..")){
                    break;
                }
            }
            if ((fd_dir.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) {
                str_subdir = wc2str(fd_dir.cFileName);
                ret = queryDIR(dir_name + "\\" + str_subdir);
            }
        }
    } while(::FindNextFile(hFind_dir, &fd_dir));

    //iterate same layer files
    do {
        if (!(fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) {
            str_tmp = wc2str(fd.cFileName);
            string fname = dir_name + "\\" + str_tmp;
            sameLayerFiles.push_back(fname);
        }
    } while(::FindNextFile(hFind, &fd));

    for (std::vector<string>::iterator it=sameLayerFiles.begin(); it!=sameLayerFiles.end(); it++) {
        std::cout << "iterated file:" << *it << "..." << std::endl;
        //Doing something with every file here
    }
    return true;
}

希望我的代码可以帮助:)

您可以在 My GitHub 上 查看更多详细信息和程序屏幕截图

原文由 Mou 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题