2 Replies - 40467 Views - Last Post: 20 December 2015 - 01:45 AM

#1 Aphex19   User is offline

  • Born again Pastafarian.
  • member icon

Reputation: 619
  • View blog
  • Posts: 1,873
  • Joined: 02-August 09

List all file names in a directory

Posted 23 September 2012 - 09:37 PM

Description: Compiles with G++ or Visual C++.This snippet is Windows specific.

'GetFileNamesInDirectory' takes a directory path and returns all the file and directory names inside that directory, inside a vector of strings.

See the "Remarks" here (http://msdn.microsoft.com/en-us/library/windows/desktop/aa364418%28v=vs.85%29.aspx) for information on the directory path which should be passed. Put simply, to retrieve all the files in a given directory, append the wildcard character '*' to the end of the path. For example, to list files in "C:/", you would pass the directory string "C:/*".

I have included a small example 'main' that will list all files in the current program's directory.
#include <Windows.h>
#include <vector>
#include <iostream>

std::vector<std::string> GetFileNamesInDirectory(std::string directory) {
	std::vector<std::string> files;
	WIN32_FIND_DATA fileData; 
	HANDLE hFind; 

	if ( !((hFind = FindFirstFile(directory.c_str(), &fileData)) == INVALID_HANDLE_VALUE) ) {
		while(FindNextFile(hFind, &fileData)) {
			files.push_back(fileData.cFileName);
		}
	}
	
	FindClose(hFind);
	return files;
}

int main() {
	std::vector<std::string> vFileNames = GetFileNamesInDirectory("*");
	for (int i = 0; i < vFileNames.size(); i++) {
		std::cout << vFileNames[i] << std::endl;
	}
	return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: List all file names in a directory

#2 NathanMullenax   User is offline

  • D.I.C Head
  • member icon

Reputation: 103
  • View blog
  • Posts: 218
  • Joined: 23-September 12

Re: List all file names in a directory

Posted 18 January 2015 - 01:49 PM

Have you checked into dirent.h for Visual Studio? It provides compatibility with a standard POSIX directory interface for Windows. There are other projects that do this sort of thing as well. You could use MinGW or Boost. In any case, you'll probably be using a third party library to get it to work cross-platform.
Was This Post Helpful? 0
  • +
  • -

#3 rasil9kudu   User is offline

  • New D.I.C Head
  • member icon

Reputation: 1
  • View blog
  • Posts: 41
  • Joined: 19-December 15

Re: List all file names in a directory

Posted 20 December 2015 - 01:45 AM

What is G++ in ur post
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1