简体   繁体   中英

List all files recursively function in MFC error?

I want to list all my files and folders (include sub-folders) and show it into my list box so I think about writing a recursive function to display them. But the code work well if I show all files and folders in the selecting folder, but it can not scan in sub-folders (it show only the first folder and no more). Please help me to know what is the error?

This is my function (I add it into my Dialog class)

void CFileListingDlg::ListFile(CString path)
{
    CFileFind hFile;
    BOOL bFound;
    CString filePath;
    bFound=hFile.FindFile(path+L"\\*.*");
    while(bFound)
    {
        bFound=hFile.FindNextFile();
        if(!hFile.IsDots())
        {
            m_lFiles.AddString(hFile.GetFilePath());

            //It work well with selecting folder if I remove this line
            //But it shows only first folder when I use it
            if(hFile.IsDirectory()) ListFile(hFile.GetFilePath()+L"\\*.*");

        }
    }
}

And then, I call it when click Browser button with the code

void CFileListingDlg::OnBnClickedBtnBrowse()
{
    // TODO: Add your control notification handler code here
    // TODO: Add your control notification handler code here
    CFolderPickerDialog folderDialog(_T("E:\\Test"));
    if(folderDialog.DoModal()==IDOK)
    {
        m_eFolder.SetWindowText(folderDialog.GetPathName());
        m_lFiles.ResetContent();
        ListFile(folderDialog.GetPathName());
    }
}

Here is the proper way to implement recursive files listing:

void ListFiles(const CString& sPath, CStringArray& files)
{
   CFileFind finder;

   // build a string with wildcards
   CString sWildcard(sPath);
   sWildcard += _T("\\*.*");

   BOOL bWorking = finder.FindFile(sWildcard);

   while (bWorking)
   {
      bWorking = finder.FindNextFile();

      // skip . and .. files; otherwise, we'd
      // recur infinitely!

      if (finder.IsDots())
         continue;

      // if it's a directory, recursively traverse it

      if (finder.IsDirectory())
      {
         CString sFile = finder.GetFilePath();
         files.Add(sFile);
         ListFiles(sFile, files);
      }
   }

   finder.Close();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM