Hi,
I'm trying to count files in a desired directory using MFC...
I tried the following code:
int CountFiles(const std::string &refcstrRootDirectory,
const std::string &refcstrExtension,
bool bSubdirectories = true)
{
int iCount = 0;
std::string strFilePath; // Filepath
std::string strPattern; // Pattern
//std::string strExtension; // Extension
HANDLE hFile; // Handle to file
WIN32_FIND_DATA FileInformation; // File information
std::string DoublebackSlash = "\\";
strPattern = refcstrRootDirectory + "\\*.*";
hFile = ::FindFirstFile(strPattern.c_str(), (&FileInformation));
if(hFile != INVALID_HANDLE_VALUE)
{
do
{
if(FileInformation.cFileName[0] != '.')
{
strFilePath.erase();
strFilePath = refcstrRootDirectory;// + "\\" +FileInformation.cFileName;
strFilePath += DoublebackSlash;
CString cfilename(FileInformation.cFileName);
CT2CA pszConvertedAnsiString(cfilename);
std::string str (pszConvertedAnsiString);
strFilePath += str;
if(FileInformation.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
{
if(bSubdirectories)
{
// Search subdirectory
int iRC = CountFiles(strFilePath,
refcstrExtension,
bSubdirectories);
if(iRC != -1)
iCount += iRC;
else
return -1;
}
}
else
{
// Check extension
CString cs(FileInformation.cFileName);
//USES_CONVERSION;
// Convert a TCHAR string to a LPCSTR
CT2CA pszConvertedAnsiString(cs);
// construct a std::string using the LPCSTR input
std::string strExtension (pszConvertedAnsiString); //Extension
strExtension = strExtension.substr(strExtension.rfind(".") + 1);
if((refcstrExtension == "*") ||
(strExtension == refcstrExtension))
{
// Increase counter
++iCount;
}
}
}
} while(::FindNextFile(hFile, &FileInformation) == TRUE);
// Close handle
::FindClose(hFile);
}
return iCount;
}
but i got the following error:
hFile = ::FindFirstFile(strPattern.c_str(), (&FileInformation));
Error 4 error C2664: 'FindFirstFileW' : cannot convert parameter 1 from 'const char *' to 'LPCWSTR'
I tried to pass it in a Unicode string using _T(""), L""
hFile = ::FindFirstFile(_T(strPattern.c_str()), (&FileInformation));
but nothing happened...
here's the calling for the function:
void CSoundProjectDlg::OnBnClickedButton2()
{
int iNumberOfFiles = 0;
// Count all files in 'c:' and its subdirectories
iNumberOfFiles = CountFiles("c:", "*");
if(iNumberOfFiles == -1)
{
// fire an error
}
// Print results
// Count '.avi' files in 'c:'
iNumberOfFiles = CountFiles("c:", "avi", false);
if(iNumberOfFiles == -1)
{
// fire an error
}
// Print results
}
Thanks,