getDirectoryContent(Directory,...,FileExtension)

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
Post Reply
gfxstyler
Posts: 222
Joined: Tue Apr 18, 2006 11:47 pm

getDirectoryContent(Directory,...,FileExtension)

Post by gfxstyler »

I made this function to get the content of directories. It can filter out specific files according to file-extensions and append the directory to the file-string.

usage:

Code: Select all

std::vector<std::string> Files = getDirectoryContent(Directory, Append Directory String to Output, File Extension);
Append-Flag is false by default.
Extension-String is "" by default, which means any files.

example:

Code: Select all

//will return a list which contains "config.cfg" for example
std::vector<std::string> Configs = getDirectoryContent(".", false, ".cfg");

//will return a vector which contains "../data/saves/bla.sav" for example
std::vector<std::string> SaveGames = getDirectoryContent("../data/saves", true, ".sav");
code:

Code: Select all

#include<iostream>
#include<string>
#include<vector>
#include<dirent.h>

std::vector<std::string> getDirectoryContent(const std::string pDir, 
const bool pAppendDirectory = false, const std::string pExt = "")
{
	std::vector<std::string> Values;
	std::vector<std::string> Files;
	
	DIR* Directory;
	dirent* CurrentFile;
	
	if(!(Directory = opendir(pDir.c_str()))) 
	{
		std::cout << "error: could not open directory: " << pDir << std::endl;
	}
	else
	{	
		while(CurrentFile = readdir(Directory))
		{
			string File = CurrentFile->d_name;
			
			//workaround: . = current directory sign, .. = parent directory sign		
			if(File != "." && File != "..")
				Files.push_back(File);
		}
		
		closedir(Directory);
		
		if(pExt != "")
		{	
			for(unsigned int i = 0; i != Files.size(); ++i)
			{
				if(Files[i].size() > pExt.size())
				{
					const string File	= Files[i];
					const int Size		= File.size();
					
					std::string Extension = "";
					
					for(unsigned int j = 0; j != pExt.size(); ++j)
						Extension += File[Size-(pExt.size()-j)];
					
					if(Extension == pExt)
						Values.push_back(File);
				}				 
			}
		}
		else
		{
			Values = Files;
		}
		
		if(pAppendDirectory)
		{
			for(unsigned int i = 0; i != Values.size(); ++i)
				Values[i] = pDir + Values[i];
		}
	}
	
	return Values;
}
Post Reply