Hello,
Is there a function that return all file in directory ???
I need the name of all files in one directory.
thanks to help me.
Printable View
Hello,
Is there a function that return all file in directory ???
I need the name of all files in one directory.
thanks to help me.
There is no C++ standard function for this operation. Depends on OS. If you are using Windows use FindFirstFile and FindNextFile API functions. If you are using Windows with MFC try the CfileFind class.
Regards,
As mentioned there is no platform independent way...
For a windows system you can use the following...The following sample does a search for all .avi-files on drive c:\.
Code:#include <string>
#include <vector>
#include <iostream>
#include <conio.h>
using std::cout;
using std::endl;
using std::string;
using std::vector;
int SearchDirectory(vector<string> &refvecFiles,
const string &refcstrRootDirectory,
const string &refcstrExtension)
{
string strFilePath; // Filepath
string strPattern; // Pattern
HANDLE hFile; // Handle to file
WIN32_FIND_DATA FileInformation; // File information
strPattern = refcstrRootDirectory + "\\*." + refcstrExtension;
hFile = ::FindFirstFile(strPattern.c_str(), &FileInformation);
if(hFile != INVALID_HANDLE_VALUE)
{
do
{
if(FileInformation.cFileName[0] != '.')
{
strFilePath.erase();
strFilePath = refcstrRootDirectory + "\\" + FileInformation.cFileName;
if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
// Search subdirectory
int iRC = SearchDirectory(refvecFiles, strFilePath, refcstrExtension);
if(iRC)
return iRC;
}
else
{
// Save filename
refvecFiles.push_back(strFilePath);
}
}
} while(::FindNextFile(hFile, &FileInformation) == TRUE);
// Close handle
::FindClose(hFile);
DWORD dwError = ::GetLastError();
if(dwError != ERROR_NO_MORE_FILES)
return dwError;
}
return 0;
}
int main()
{
vector<string> vecFiles;
// Search 'c:' for '.avi' files
int iRC = SearchDirectory(vecFiles, "c:", "avi");
if(iRC)
{
cout << "Error " << iRC << endl;
return -1;
}
// Print results
for(vector<string>::iterator iter = vecFiles.begin();
iter != vecFiles.end();
++iter)
cout << *iter << endl;
// Wait for keystroke
_getch();
return 0;
}