Download Quick Currency Converter


Traverse Directory (C++)

Description: This project teaches you how to traverse a given directory recursively. The sample project will print every file name inside the directory; it will recurse the directories inside the specified directory, and then inside these directories and so on until it has traversed all the files. This code will work only on Windows as it uses Win32 API calls for reading directory. If you are on Unix-based system, you can check our project Duplicate File Finder to learn how to traverse a directory in a Unix-based system.

Difficulty: Medium

Language: C++

Compiler/IDE: Visual Studio, dev C++ (others will work as well)



View Source

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

using namespace std;
DWORD WINAPI GetAllFiles(void *args);

int main()
{
    char path[] = "E:";
    CreateThread(NULL, 0, GetAllFiles, (void *)path, 0, NULL); 
    				
    system("pause");
}

DWORD WINAPI GetAllFiles(void *args)
{
    char *tmpPath = (char *) args;
    string sPath(tmpPath);
 
    WIN32_FIND_DATA FindFileData;
    string sTmpPath = sPath;
    sTmpPath += "\\*.*";
   
    string currFile = "";

    HANDLE hFind = FindFirstFile(sTmpPath.c_str(), &FindFileData );
    if (hFind == INVALID_HANDLE_VALUE) {
        cout<< "Not a valid path\n";
        return 0;}
    else 
    {
        do 
        {  
           //check if its a directory...
            if ((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY ))
            {
                string filePath = FindFileData.cFileName;	
                                        //ignore '.' and '..'
            	if (strcmp(".", filePath.c_str()) && strcmp("..", filePath.c_str()))             
                                        {
                                              //Dont list recycle bin content...
		 if (filePath == "$RECYCLE.BIN" || filePath == "$Recycle.Bin")
                     continue;
		     sTmpPath = sPath + "\\" + filePath;
                     GetAllFiles((void *) sTmpPath.c_str());
                }
            }
            else                       //its a file...
            {
		sTmpPath = sPath + "\\";
		currFile = sTmpPath + FindFileData.cFileName;
				
                cout << currFile << endl << endl;
            }												
        } while (FindNextFile(hFind, &FindFileData) != 0);

        FindClose(hFind);

    }

    return 0;
}


Notes:The project calls a thread GetAllFiles() (You can convert it into a normal function, instead of a thread, if you want to). To find file name, you need to be familiar with two win32 functions: FindFirstFile() and FindNextFile().

FindFirstFile(), as the name implies, finds the first file that matches a given pattern. Here we've instructed this function to find every file inside the specified directory by using wildcard "*". This function returns a handle object that is used in further calls to FindNextFile(), which of course finds the next file in the directory. You need to loop using this function until you get false. Both these function receives an argument of type ' WIN32_FIND_DATA' and fills this object after success. This object contains important data about the file including 'cFileName' which holds the name of the file.

Here is the main logic
(1) Find a file (please note that file here refers to a path, it can be a file or folder).
(2) Check to see if its a directory or a file.
(3) If its a file, simple print its name; if its a directory, recurse through the same function GetAllFiles() that will find all the files inside this directory.

A simple question is: why on earth would you want to print all file names on your hard drive? Well it's nothing but a sample project. It tells you how to get file name and then you can perform all sorts of operations on those files. For example: you can read files; you can count them; you can write those files name on a file and then print them; you can even scan them using an anti-virus. Our software Media Locater uses the exact same function (GetAllFiles()) to get the file names inside a directory.

A word of caution: This project scans drive E:. Make sure you change it to a suitable path on your hard drive before running the program. You can type any valid path. e,g 'C:\Windows'