Amir Youhana Amir Youhana - 8 days ago 4
C++ Question

find list of files in a directory programmatically C++ MFC

I'm trying to find list of files in a directory programmatically and I've written the following code

CStringArray CCL2ProjectDirectoryPage::GetAllFilesNames()
{
WIN32_FIND_DATA fileData;
memset(&fileData, 0, sizeof(WIN32_FIND_DATA));
HANDLE handle = FindFirstFile("d:\\test\\*", &fileData);

CStringArray strArray;

while(handle != INVALID_HANDLE_VALUE)
{
strArray.Add(fileData.cFileName); // the problem is that the fileData.cFileName always contains "."

if(FALSE == FindNextFile(handle, &fileData))
break;
}
FindClose(handle);

return strArray;
}


The problem is that the fileData.cFileName always contains ".".
"." with the first file, ".." with the second file and so on.
what is wrong with this code?
Thanks in advance.

Answer

You want this:

CStringArray CCL2ProjectDirectoryPage::GetAllFilesNames()
{
  WIN32_FIND_DATA fileData;
  memset(&fileData, 0, sizeof(WIN32_FIND_DATA));
  HANDLE handle = FindFirstFile("d:\\test\\*", &fileData);
  CStringArray strArray;

  if (handle != INVALID_HANDLE_VALUE)
  {
    do
    {
      if (_tcscmp(fileData.cFileName, _T(".") != 0 && // ignore "." and ".."
          _tcscmp(fileData.cFileName, _T("..") != 0)
      {
        strArray.Add(fileData.cFileName);
      }
    } while (FindNextFile(handle, &fileData))

    FindClose(handle);    
  }

  return strArray;
}

Disclaimer: this is untested and minimal error checking code just for demonstration purposes.