Listing only folders in directory

自作多情 提交于 2019-12-13 11:37:52

问题


I want to list folders in a directory in C++, ideally in a portable (working in the major Operating Systems) way. I tried using POSIX, and it works correctly, but how can i identify whether the found item is a folder?


回答1:


Using the C++17 std::filesystem library:

std::vector<std::string> get_directories(const std::string& s)
{
    std::vector<std::string> r;
    for(auto& p : std::filesystem::recursive_directory_iterator(s))
        if (p.is_directory())
            r.push_back(p.path().string());
    return r;
}



回答2:


You could use opendir() and readdir() to list directories and subdirectories. The following example prints all subdirectories inside the current path:

#include <dirent.h>
#include <stdio.h>

int main()
{
    const char* PATH = ".";

    DIR *dir = opendir(PATH);

    struct dirent *entry = readdir(dir);

    while (entry != NULL)
    {
        if (entry->d_type == DT_DIR)
            printf("%s\n", entry->d_name);

        entry = readdir(dir);
    }

    closedir(dir);

    return 0;
}



回答3:


Here follows a (slightly modified) quote from the boost filesystem documentation to show you how it can be done:

void iterate_over_directories( const path & dir_path )         // in this directory,
{
  if ( exists( dir_path ) ) 
  {
    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()) )
      {
        //... here you have a directory
      }
    }
  }
}



回答4:


Look up the stat function. Here is a description. Some sample code:

struct stat st;
const char *dirname = "dir_name";
if( stat( dirname, &st ) == 0 && S_ISDIR( st.st_mode ) ) {
    // "dir_name" is a subdirectory of the current directory
} else {
    // "dir_name" doesn't exist or isn't a directory
}



回答5:


I feel compelled to mention PhysFS. I just integrated it into my own project. It provides true cross-platform (Mac / Linux / PC) file operations and can even unpack various archive definitions such as zip, 7zip, pak, and so on. It has a few functions (PHYSFS_isDirectory, PHYSFS_enumerateFiles) which can determine what you are asking for as well.




回答6:


Under Windows, you can use _findfirst() and _findnext() to iterate through the contents of a directory, and then use CreateFile() and GetFileInformationByHandle() to determine whether a particular entry is a directory or a folder. (Yes, CreateFile(), with the appropriate arguments, to examine an existing file. Ain't life grand?)

For reference, some classes where I implemented code that uses those calls can be seen here and here



来源:https://stackoverflow.com/questions/5043403/listing-only-folders-in-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!