Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing only folders in directory

Tags:

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?

like image 320
m4tx Avatar asked Feb 18 '11 15:02

m4tx


People also ask

How do I list only directories in current directory?

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.

How do I get a list of folders in a folder?

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.

How do I show only directories in CMD?

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.

Which command is used for to list only directories?

The ls command is used to list files or directories in Linux and other Unix-based operating systems.


2 Answers

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; } 
like image 99
davidag Avatar answered Nov 09 '22 05:11

davidag


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; } 
like image 26
wally Avatar answered Nov 09 '22 03:11

wally