Link to home
Start Free TrialLog in
Avatar of V2dB
V2dB

asked on

Listing files in a folder


How can I get a list of all the files in a given folder?

In VB this can be done usig the Filesystem object, but im not sure how it can be done in MFC.

Thanks.
Avatar of jkr
jkr
Flag of Germany image

Hi,
The following function adds the folder file list to a ListCtrl :

CString m_csPath;//The path of  folder
WIN32_FIND_DATA FileData;
HANDLE hSearch;
DWORD dwAttrs;
BOOL fFinished = FALSE;

      CString str;
// Start searching for .TXT files in the current directory.
      str.Format("%s\\*.txt",m_csPath);
hSearch = FindFirstFile(str, &FileData);
if (hSearch == INVALID_HANDLE_VALUE)
{
    AfxMessageBox("No files found.");
      return;
}
 
// Copy each .TXT file to the new directory
// and change it to read only, if not already.
 CString cs;
while (!fFinished)
{
      cs.Format("%s\\%s",m_csPath,FileData.cFileName);
      if(PathIsDirectory(cs))
            cs.Format("[%s]",FileData.cFileName);
      else
      cs=FileData.cFileName;

if(FileData.cFileName=="." || FileData.cFileName=="..");
else{
//Here I add it to a list control       
m_listDir.AddString(cs);
}

    if (!FindNextFile(hSearch, &FileData))
    {
        if (GetLastError() == ERROR_NO_MORE_FILES)
        {
//            AfxMessageBox( "No more files.");
            fFinished = TRUE;
        }
        else
        {
            AfxMessageBox("Couldn't find next file.");
        }
    }
}

Good Luck!
ASKER CERTIFIED SOLUTION
Avatar of Priyesh
Priyesh

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Hi 'V2dB',
Would you please explain, what is the difference between my comment and the accepted answer?

Thanks!
Avatar of V2dB
V2dB

ASKER

Nass89,

I was looking for the MFC way to do this.. I looked at all 3 comments, and the CFileFind method was the easiest as it provides some useful methods to get file information such as IsDirectory(), it was also less code, he provided a complete and working function and it was also the MFC way of doing it.

Thank you!