I don't suppose there is another way to list the directory contents?
Main Topics
Browse All TopicsI would like to list the contents of a directory using c++, but I am at a loss as to how to go about doing this. I do not know if there is a header I could include to make thing easier.
This is about as far as I have got so farI just don't have any idea on how to go about listing files in a directory
string *My_File::Scan_Directory(s
{
}
So any help will be appreciated
This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.
Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.
If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.
Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.
Access the answers to your technology questions today.
30-day free trial. Register in 60 seconds.
Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Try it out and discover for yourself.
30-day free trial. Register in 60 seconds.
Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.
>>>> I don't suppose there is another way to list the directory contents?
#include <process.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std;
int getFilesFromDir(const string& path, vector<string>& files)
{
string cmd = "dir /b \"";
cmd += path; // expect something like c:/mypath
cmd += "\" > c:/temp/dir.txt";
system(cmd.c_str());
ifstream ifs("c:/temp/dir.txt");
string line;
while (getline(ifs, line))
files.push_back(line);
remove("c:/temp/dir.txt");
return files.size();
}
Regards, Alex
hi broken_array,
here is an example (adapted from own code, untested!)
>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>
enum DirItemType
{
DirItemUndefined = 0x0,
DirItemDir = 0x1,
DirItemFile = 0x2,
};
static void Dump_Dir_Item( const char *pszPath, const char *pszFilename, DirItemType type )
{
printf( "%s\\%s\n", pszPath, pszFilename );
}
bool My_File::Scan_Directory(st
{
DirItemType itemType;
struct _finddata_t c_file;
long hFile;
static const int DIRECTORY = _A_SUBDIR;
static const int FILE = _A_NORMAL | _A_RDONLY | _A_HIDDEN | _A_SYSTEM | _A_ARCH;
hFile = _findfirst( dir.c_str(), &c_file );
if( hFile == -1 ) return false;
if( strcmp( c_file.name, "." ) && strcmp( c_file.name, ".." ) )
{
if( ( ( type & DirItemDir ) && ( c_file.attrib & DIRECTORY ) ) ||
( ( type & DirItemFile ) && ( c_file.attrib & FILE || c_file.attrib == 0 ) ) )
{
if( c_file.attrib & DIRECTORY )
{
itemType = DirItemDir;
}
else if( c_file.attrib & FILE || c_file.attrib == 0 )
{
itemType = DirItemFile;
}
else assert( false );
Dump_Dir_Item( dir.c_str(), c_file.name, itemType );
}
}
while( _findnext( hFile, &c_file ) == 0 )
{
if( strcmp( c_file.name, "." ) && strcmp( c_file.name, ".." ) )
{
if( ( ( type & DirItemDir ) && ( c_file.attrib & DIRECTORY ) ) ||
( ( type & DirItemFile ) && ( c_file.attrib & FILE || c_file.attrib == 0 ) ) )
{
if( c_file.attrib & DIRECTORY )
{
itemType = DirItemDir;
}
else if( c_file.attrib & FILE || c_file.attrib == 0 )
{
itemType = DirItemFile;
}
else assert( false );
Dump_Dir_Item( dir.c_str(), c_file.name, itemType );
}
}
}
return true;
}
<<<<<<<<<<<<<<<<<<<<<<<<<<
hope it helps,
ike
oops, adapted too fast ;-) with second param of My_File::Scan_Directory, you can control, if files should be printed, directories or both
>>>>>>>>>>>>>>>>>>>> code begin >>>>>>>>>>>>>>>>>>>>>>>>
#include <io.h>
#include <stdio.h>
#include <assert.h>
enum DirItemType
{
DirItemUndefined = 0x0,
DirItemDir = 0x1,
DirItemFile = 0x2,
};
static void Dump_Dir_Item( const char *pszPath, const char *pszFilename, DirItemType type )
{
printf( "%s\\%s\n", pszPath, pszFilename );
}
bool My_File::Scan_Directory(st
{
DirItemType itemType;
struct _finddata_t c_file;
long hFile;
static const int DIRECTORY = _A_SUBDIR;
static const int FILE = _A_NORMAL | _A_RDONLY | _A_HIDDEN | _A_SYSTEM | _A_ARCH;
hFile = _findfirst( dir.c_str(), &c_file );
if( hFile == -1 ) return false;
if( strcmp( c_file.name, "." ) && strcmp( c_file.name, ".." ) )
{
if( ( ( type & DirItemDir ) && ( c_file.attrib & DIRECTORY ) ) ||
( ( type & DirItemFile ) && ( c_file.attrib & FILE || c_file.attrib == 0 ) ) )
{
if( c_file.attrib & DIRECTORY )
{
itemType = DirItemDir;
}
else if( c_file.attrib & FILE || c_file.attrib == 0 )
{
itemType = DirItemFile;
}
else assert( false );
Dump_Dir_Item( dir.c_str(), c_file.name, itemType );
}
}
while( _findnext( hFile, &c_file ) == 0 )
{
if( strcmp( c_file.name, "." ) && strcmp( c_file.name, ".." ) )
{
if( ( ( type & DirItemDir ) && ( c_file.attrib & DIRECTORY ) ) ||
( ( type & DirItemFile ) && ( c_file.attrib & FILE || c_file.attrib == 0 ) ) )
{
if( c_file.attrib & DIRECTORY )
{
itemType = DirItemDir;
}
else if( c_file.attrib & FILE || c_file.attrib == 0 )
{
itemType = DirItemFile;
}
else assert( false );
Dump_Dir_Item( dir.c_str(), c_file.name, itemType );
}
}
}
return true;
}
<<<<<<<<<<<<<<<<<<<<<<<<<<
ike
Check out the following code, that is portable on Windows, UNIX, Linux, and any other POSIX operating system:
http://code.axter.com/find
Example usage:
FindFilesInPath MyFindFilesInPath("M:\\Bin
for(std::vector<std::strin
i != MyFindFilesInPath.c_FileLi
{
cout << i->c_str() << endl;
}
I have looked at http://msdn.microsoft.com/
string *My_File::Scan_Directory(s
{
string *Files;
int count = 0;
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
string DirSpec; // directory specification
DWORD dwError;
cout << "Target directory is " << dir << endl;
DirSpec = dir;
DirSpec.append("\\*");
hFind = FindFirstFile(DirSpec.c_st
if (hFind == INVALID_HANDLE_VALUE)
{
cout << "Invalid file handle. Error is " << GetLastError() << endl;
return (0);
}
else
{
cout << "First file name is " << FindFileData.cFileName << endl;
count = 1;
while(FindNextFile(hFind, &FindFileData) != 0)
{
cout << "Next file name is " << FindFileData.cFileName << endl;
count++;
}
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
cout << "FindNextFile error. Error is " << dwError <<endl;
return (0);
}
}
Files = new string[count];
count = 0;
hFind = FindFirstFile(DirSpec.c_st
if (hFind == INVALID_HANDLE_VALUE)
{
cout << "Invalid file handle. Error is " << GetLastError() << endl;
return (0);
}
else
{
Files[count] = FindFileData.cFileName;
while(FindNextFile(hFind, &FindFileData) != 0)
{
count++;
Files[count] = FindFileData.cFileName;
}
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
cout << "FindNextFile error. Error is " << dwError <<endl;
return (0);
}
}
return (Files);
}
I have altered the code so that the files that are found in the directory are stored in a vector called Directory_Files. I still have the problem that the folders that exist within the directory that is beeing scanned are not expanded, the files in these folders are not scanned and so are not put into the vector.
bool My_File::Scan_Directory(st
{
WIN32_FIND_DATA FindFileData;
HANDLE hFind = INVALID_HANDLE_VALUE;
string DirSpec; // directory specification
DWORD dwError;
//cout << "Target directory is " << dir << endl;
DirSpec = dir;
DirSpec.append("\\*");
Directory_Files.erase(Dire
hFind = FindFirstFile(DirSpec.c_st
if (hFind == INVALID_HANDLE_VALUE)
{
cout << "Invalid file handle. Error is " << GetLastError() << endl;
return (false);
}
else
{
//cout << "First file name is " << FindFileData.cFileName << endl;
Directory_Files.push_back(
while(FindNextFile(hFind, &FindFileData) != 0)
{
//cout << "Next file name is " << FindFileData.cFileName << endl;
Directory_Files.push_back(
}
dwError = GetLastError();
FindClose(hFind);
if (dwError != ERROR_NO_MORE_FILES)
{
cout << "FindNextFile error. Error is " << dwError <<endl;
return (false);
}
}
return (true);
}
I think I need to somehow search through any folders that are in the directory to be scanned and list the files in theses folders as well, but I am not sure how to do this.
>> I still have the problem that the folders that exist within the directory that is beeing scanned are not expanded, the files in these folders are not scanned and so are not put into the vector.
The code I posted has the option to expand to sub directories.
This option is the last argument in the constructor.
bool SearchSubDir = true;
FindFilesInPath MyFindFilesInPath("M:\\Bin
here's my 2 cents
#pragma warning(disable:4786)
#include <vector>
#include <string>
#include <iostream>
#include <windows.h>
using namespace std;
//////////////////////////
void searchFolders(string &folder, vector<string> &vstring)
{
WIN32_FIND_DATA FindData;
string store;
if(folder=="")
return;
if(folder[folder.size()-1]
folder += "\\";
//if there is something worth looking at...
string tmpfolder = folder;
tmpfolder += "*.*";
HANDLE hFind = FindFirstFile(tmpfolder.c_
if (hFind != INVALID_HANDLE_VALUE)
{
//go through all the results...
do
{
string szFileName(FindData.cFileN
if (FindData.dwFileAttributes
{
if (szFileName != "." && szFileName != "..")
searchFolders(folder + szFileName, vstring);
}
else
{
//if(szFileName.find(".exe
//{
store = folder + szFileName;
vstring.push_back(store);
//}
}
}
while(FindNextFile(hFind, &FindData));
FindClose(hFind);
}
}
int main(int argc, char* argv[])
{
char yn = 0;
vector<string> files;
vector<string>::iterator siter;
string folder("c:\\windows\\");
cout<<"Searching "<<folder.c_str()<<endl;
searchFolders(folder, files);
cout<<files.size()<<" files found.\nWould you like to list them?\n";
yn = cin.get();
if(yn == 'y' || yn == 'Y')
{
for(siter = files.begin(); siter != files.end(); ++siter)
cout<<siter->c_str()<<endl
}
return 0;
}
Business Accounts
Answer for Membership
by: AlexFMPosted on 2005-08-03 at 04:57:18ID: 14587361
For Windows platform:
library/de fault.asp? url=/libra ry/ en-us/f ileio/fs/l isting_the _files_in_ a_director y.asp library/de fault.asp? url=/libra ry/ en-us/f ileio/fs/f indfirstfi le.asp
http://msdn.microsoft.com/
http://msdn.microsoft.com/