4/26/2016 - 8:45 AM

C++ directory lister

C++ directory lister

#include <stdio.h>
#include <string>
#include <iostream>
#include <windows.h>
#include <vector>

using namespace std;

//Simple struct to return from lsfiles
struct List {
	vector<string> files;
	vector<string> folders;
//All of the hard work
struct List lsfiles(string folder)  //(c)
    vector<string> files; //Will be added to List
	vector<string> folders; //Will be added to List
    char search_path[200];
    sprintf(search_path, "%s*.*", folder.c_str());
    WIN32_FIND_DATA fd; 
    HANDLE hFind = ::FindFirstFile(search_path, &fd); 
    if(hFind != INVALID_HANDLE_VALUE) 
            // read all (real) files in current folder, delete '!' read other 2 default folder . and ..
            if(! (fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ) 
            } else //Put folders into vector
        }while(::FindNextFile(hFind, &fd)); 
	List me;
	me.files = files;
	me.folders = folders;
    return me;

int main(int argc, char *argv[])
	string where;
	if(argc > 1){where = argv[1] + string("\\");}else{where = "";}
	List you = lsfiles(where); //Get contents of directory
	vector<string>::iterator files_begin = you.files.begin();
	vector<string>::iterator files_end = you.files.end();
	vector<string>::iterator folders_begin = you.folders.begin();
	vector<string>::iterator folders_end = you.folders.end();
	for(; folders_begin != folders_end; folders_begin++){
		cout << "[D] " << *folders_begin << "\n";
	for(; files_begin != files_end; files_begin++){
		cout << "[F] " << *files_begin << "\n";
	return 0;

/////////Example output
//PS C:\> mls
//[D] $Recycle.Bin
//[D] adobeTemp
//[D] AMD
//[D] android-sdk
//[D] apache-ant-1.9.3
//[D] Documents and Settings
//[D] FWBuilder51
//[D] inetpub
//[D] iSCSIVirtualDisks
//[D] Media
//[D] MinGW-4.8.1
//[D] MSOCache
//[D] PerfLogs
//[D] Program Files
//[D] Program Files (x86)
//[D] ProgramData
//[D] Python27
//[D] Sandbox
//[D] System Volume Information
//[D] TFTP-Root
//[D] UnitTest++-1.3
//[D] Users
//[D] vz
//[D] Windows
//[F] bootmgr
//[F] pagefile.sys
//PS C:\> mls AMD
//[D] .
//[D] ..
//[D] AMD_Catalyst_12.6_Legacy_Win8
//PS C:\>