• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 275
  • Last Modified:

Retrieving file names based on extention

Does anyone have a generic C, C++, or MFC routine that I can use to get all the file names in a directory with a certain file extention?  Similar to the way the CFileDialog class gleens out files based on extention.
0
johnsla
Asked:
johnsla
2 Solutions
 
jackrabbit22Commented:
Try using FindFirstFile, FindNextFile...

void ListFolderContents(LPCTSTR lpszFolderPath, const CString& strExt, CStringArray& fileListing)
{
     // lpszFolderPath - path of folder to get files from (i.e. C:\Windows\Desktop\) - you must include trailing slash on the path!
     // strExt - file extension to look for (i.e. *.txt)
     // fileListing - holds the files matching the extension

    WIN32_FIND_DATA findData;

    // Add the wildcard extension
    TCHAR curFolder[MAX_PATH];
    _tcscpy(curFolder, lpszFolderPath);
    _tcscat(curFolder, strExt);

    HANDLE handle = FindFirstFile(curFolder, &findData);

    if (handle == INVALID_HANDLE_VALUE)
         return;

    // Process all files within current directory
    do
    {
         // Add file to our array
         fileListing.Add(findData.cFileName);
    } while (FindNextFile(handle, &findData));

FindClose(handle);
}      

Usage:
// This gets all .txt files on the desktop:

CStringArray fileListing;
ListFolderContents(_T("C:\\Windows\\Desktop\\"), _T("*.txt"), fileListing);

     for (int i = 0; i < fileListing.GetSize(); i++)
          TRACE(_T("Filename: %s\n"), fileListing[i]);
0
 
sreenu_v78Commented:
hai
use CFileFind like this way

#include <direct.h>//for chdir()
CFileFind finder;
CString strpath;

chdir(strpath); //path of directory
   BOOL bWorking = finder.FindFile("*.exe");//this find the file with extension exe only.
   while (bWorking)
   {
      bWorking = finder.FindNextFile();
      cout << (LPCTSTR) finder.GetFileName() << endl;
   }

featch the all files with extension .exe in the specified directory.
cheers..
sreenu.
0
 
johnslaAuthor Commented:
I thank you both for your solutions.  Because sreenu v78 was the first to respond I should award him the points but thank you jackrabbit22 as well.
0

Featured Post

Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now