Categories
code linux programming Solutions tips

Reading a directory in C++ (Win32 & Posix)

A c++ code snippet for reading a directory’s file names

Just a snippet of code if someone out there needs it. I keep coming back to it, so I thought why not share it…

#include <iostream>
#ifndef WIN32
#include <dirent.h>
#endif
using namespace std;
void open_imgs_dir(char* dir_name, std::vector<std::string>& file_names) {
	if (dir_name == NULL) {
		return;
	}
	string dir_name_ = string(dir_name);
	vector<string> files_;
#ifndef WIN32
//open a directory the POSIX way
	DIR *dp;
	struct dirent *ep;
	dp = opendir (dir_name);
	if (dp != NULL)
	{
		while (ep = readdir (dp)) {
			if (ep->d_name[0] != '.')
				files_.push_back(ep->d_name);
		}
		(void) closedir (dp);
	}
	else {
		cerr << ("Couldn't open the directory");
		return;
	}
#else
//open a directory the WIN32 way
	HANDLE hFind = INVALID_HANDLE_VALUE;
	WIN32_FIND_DATA fdata;
	if(dir_name_[dir_name_.size()-1] == '\\' || dir_name_[dir_name_.size()-1] == '/') {
		dir_name_ = dir_name_.substr(0,dir_name_.size()-1);
	}
	hFind = FindFirstFile(string(dir_name_).append("\\*").c_str(), &fdata);
	if (hFind != INVALID_HANDLE_VALUE)
	{
		do
		{
			if (strcmp(fdata.cFileName, ".") != 0 &&
				strcmp(fdata.cFileName, "..") != 0)
			{
				if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
				{
					continue; // a diretory
				}
				else
				{
					files_.push_back(fdata.cFileName);
				}
			}
		}
		while (FindNextFile(hFind, &fdata) != 0);
	} else {
		cerr << "can't open directory\n";
		return;
	}
	if (GetLastError() != ERROR_NO_MORE_FILES)
	{
		FindClose(hFind);
		cerr << "some other error with opening directory: " << GetLastError() << endl;
		return;
	}
	FindClose(hFind);
	hFind = INVALID_HANDLE_VALUE;
#endif
	file_names.clear();
	file_names = files_;
}

Enjoy
Roy.

One reply on “Reading a directory in C++ (Win32 & Posix)”

Leave a Reply

Your email address will not be published. Required fields are marked *