I am trying to display the files and folders in a directory. And if the folders have a nother folder, display those contents also, and so on.

I have this code but it isn't working the way I would like it to:

#include <Windows.h>
#include <string>
#include <iostream>

using namespace std;

int main(int argc, char* argv[])
{
    WIN32_FIND_DATA wfd;
    HANDLE hf;
    string findwhat, findwhat2;
    string path = "C:";

    findwhat = path + "\\*";

    hf = FindFirstFile(findwhat.c_str(), &wfd);

    while(hf != INVALID_HANDLE_VALUE)
    {
        if(wfd.cFileName[0] != '.' && (wfd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
        {
            string found;
            found = path + "\\" + wfd.cFileName;
            cout<<found<<endl;

            HANDLE hf2;
            WIN32_FIND_DATA wfd2;

            findwhat2 = path + findwhat + found + "\\";

            hf2 = FindFirstFile(findwhat2.c_str(), &wfd2);

            if(wfd2.cFileName[0] != '.' && (wfd2.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY))
            {
                cout<<"---->"<<wfd2.cFileName<<endl;
            }

        }

        if(!FindNextFile(hf, &wfd))
        {
            FindClose(hf);
            hf = INVALID_HANDLE_VALUE;
        }
    }

    cin.get();
}

How do I fix it?

Recommended Answers

All 3 Replies

You have to use a recursive function. I've written a code snippet that does exactly that for both MS-Windows and *nix. Or if you want to go a more portable way then use boost library.

**what is the do while (condition) and its purpose. plz tell me
i m a new student of c++ so plz guide me...

post some code, I don't know what you are talking about. If it's in my code snippet it's more than likely calling _findnexti64() until that function returns no more file names. If you don't know what a function does then you need to google for it and you will find out what it does.

Since you want to use FindFirstFile() you will have to call FindNextFile() instead of )findnexti64() that is shown in my code. Both functions do about the same thing. Also notice on each call of _findnexti64() the program checks to see if the file is a folder name, and if it is the function recursively calls itself to process all the files in that folder.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.