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 wor开发者_Python百科ks correctly, but how can i identify whether the found item is a folder?
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;
}
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;
}
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
}
}
}
}
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
}
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.
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
精彩评论