how do I list subdirectories in windows using C++? Using code that would run cross-platorm is better.
Substitute dir /A:D. /B /S > FolderList. txt to produce a list of all folders and all subfolders of the directory. WARNING: This can take a while if you have a large directory.
If you name one or more directories on the command line, ls will list each one. The -R (uppercase R) option lists all subdirectories, recursively. That shows you the whole directory tree starting at the current directory (or the directories you name on the command line).
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.
Here's a relatively good solution that should work cross platform. You'll have to change the section of the code where you want it to do something but otherwise it should work quite well.
#include <cstring>
#include <io.h>
#include <iostream>
#include <stdio.h>
using namespace std;
void list(char* dir)
{
char originalDirectory[_MAX_PATH];
// Get the current directory so we can return to it
_getcwd(originalDirectory, _MAX_PATH);
_chdir(dir); // Change to the working directory
_finddata_t fileinfo;
// This will grab the first file in the directory
// "*" can be changed if you only want to look for specific files
intptr_t handle = _findfirst("*", &fileinfo);
if(handle == -1) // No files or directories found
{
perror("Error searching for file");
exit(1);
}
do
{
if(strcmp(fileinfo.name, ".") == 0 || strcmp(fileinfo.name, "..") == 0)
continue;
if(fileinfo.attrib & _A_SUBDIR) // Use bitmask to see if this is a directory
cout << "This is a directory." << endl;
else
cout << "This is a file." << endl;
} while(_findnext(handle, &fileinfo) == 0);
_findclose(handle); // Close the stream
_chdir(originalDirectory);
}
int main()
{
list("C:\\");
return 0;
}
This is pretty concise code and will list all sub-directories and files in the directory. If you want to have it list all the contents in each sub-directory, you can recursively call the function by passing in the sub-directory on the line that prints out "This is a directory." Something like list(fileinfo.name); should do the trick.
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