The other day I had to read all the file names from a directory and I found it really difficult to write a simple program to do that. While searching I ended up at Stack Overflow and the following example is taken from here.
Note that the 'dirent.h' is not available as standard windows file and the best option is to download it from here and add it in your include directory of the project.
The program as follows:
//Program tested on Microsoft Visual Studio 2008 - Zahid Ghadialy
#include<iostream>
#pragma warning( disable : 4996 )
#include "dirent.h"
#pragma warning( default : 4996 )
using namespace std;
int main(int argc, char *argv[])
{
if(argc != 2)
{
cout<<"Usage: "<<argv[0]<<" <Directory name>"<<endl;
return -1;
}
DIR *dir;
dir = opendir (argv[1]);
if (dir != NULL)
{
cout<<"Directory Listing for "<<argv[1]<<" : "<<endl;
struct dirent *ent;
while ((ent = readdir (dir)) != NULL)
{
cout<<ent->d_name<<endl;
}
}
else
{
cout<<"Invalid Directory name"<<endl;
return -1;
}
return 0;
}
You may also encounter the following warning
warning C4996: 'strcpy': This function or variable may be unsafe. Consider using strcpy_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details.
to get rid of it, I have used the #Pragma supressor.
You may also get the following error:
error C2664: 'FindFirstFileW' : cannot convert parameter 1 from 'char *' to 'LPCWSTR'
to get rid of it, go to properties->general->Character set - default is 'Use Unicode Charachter set', change it to 'Use Multi-Byte Character Set'
The output is as follows: