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?
Linux or UNIX-like system use the ls command to list files and directories. However, ls does not have an option to list only directories. You can use combination of ls command, find command, and grep command to list directory names only. You can use the find command too.
You can use the DIR command by itself (just type “dir” at the Command Prompt) to list the files and folders in the current directory.
At a Windows command prompt, how can I show only Directories and not Files? Try DIR /B /AD or DIR /B /S /AD and see if one of those are what you're expecting result wise. You can see DIR command switches, etc.
The ls command is used to list files or directories in Linux and other Unix-based operating systems.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With