Listing files in a directory in C++

Tom Sampson

General and Tech Stuff! - Please Please leave comments! I will ALWAYS read and reply.

July 30, 2008
Filed under: C++ — tomtech999 @ 4:13 pm
Tags: C#, directory, FindFirstFile, FindNextFile, folder contents, winAPI, windows programming

First of all I am not sure how you go about doing this in unix or linux! There is no standard, platform specific way to get all the files in a directory, however the following method works on windows making use of calls to winAPI so dont forget to include this!

#include <windows.h>

The following code then loops through a folder (in this case the starting folder of the executable) and puts the filenames into a string array.  The functions FindFirstFile and FindNextFile both work by populating a structure of the type WIN32_FIND_DATA which holds all the properties of the file in question.

UINT counter(0);
bool working(true);
string buffer;
string fileName[1000];
WIN32_FIND_DATA myimage;
HANDLE myHandle=FindFirstFile("*.jpg",&myimage);
if(myHandle!=INVALID_HANDLE_VALUE)
{
buffer=myimage.cFileName;
fileName[counter]=buffer;
while(working)
{
FindNextFile(myHandle,&myimage);
if(myimage.cFileName!=buffer)
{
buffer=myimage.cFileName;
++counter;
fileName[counter]=buffer;
}
else
{
//end of files reached
working=false;
}
}
}

When the last file in the folder has been read, the FindNextFile method will keep returning the same filename over and over again in the while loop. To catch this i use a sort of swap buffer to check if the same filename is found twice, and if so exiting the loop. I am sure there is a better way to catch the last file and will look into this soon. If anyone knows a more efficient way to do this please let me know.

NOTE:- “*.jpg” could be replaced with “C:/myfolder” or “*.doc” or a combination of the two depending on how you wish to filter the files that are found.  Using “” would list all the files in the running directory of the executable.

 

 
Comments
Advertisements
Zimbio Entertainment
Copyright © 2012 - Zimbio, Inc. Some rights reserved. Coming soon: Livingly
Share
. . .
Follow
. . .