Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I list subdirectories in Windows using C++?

how do I list subdirectories in windows using C++? Using code that would run cross-platorm is better.

like image 565
avee Avatar asked May 26 '11 04:05

avee


People also ask

How do I list all subdirectories in Windows?

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.

How do I list subdirectories?

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).

How do I get a list of directories in Windows?

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.


1 Answers

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.

like image 75
legacybass Avatar answered Sep 22 '22 21:09

legacybass