Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

need list of files in directory

Status
Not open for further replies.

hugh7

Technical User
Mar 2, 2003
24
US
I need to get a list of text files on a: drive . How can I do this?
I will then load the file names into an array in order to open each file and then append to another text file.
Thanks for any ideas.


 
Scan directory pattern is:
Code:
#include <windows.h>
...
const char p[] = &quot;A:\\*.txt&quot;;
...
WIN32_FIND_DATA info;
HANDLE h;

if ((h = FindFirstFile(p,&info)) != INVALID_HANDLE_VALUE)
{
  do
  {
    // Now file name C-string is in info.cFileName array
    ...
  } while(FindNextFile(h,&info));
  FindClose(h);
}
else ... // No such files.
To scan all drive (with subdirectories) you may modify and convert this snippet into the (recursive) function, for example:
Code:
class DirList {...}; // Invent file names collector.
...
int ScanDir(const char* dir, DirList& dl)
{
  int n = 0; // Number of files scanned.
  char* pattern = new char[_MAX_PATH];
  // todo: Make dir\*.* pattern to scan ALL files and dirs
  WIN32_FIND_DATA info;
  HANDLE h;
  if ((h = ... // see above
  {
    do
    {
       if (info.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY)
       {
         // Make dir\info.cFileName in p (subdir name)
         n += ScanDir(p,dl);
       }
       else if (it's a TEXT file - check info.cFileName)
       {
          ++n;
          dl.add(info.cFileName);
       }
    while (... see above);
    ... CloseHandle etc - see above
  }
  delete [] pattern;
  return n;
}
Windows directory scanning can't filter files by attributes. You must do it in your code.
Directory scanning is a platform-dependent issue. Therefore no dirscan functionality in C++ standard library.
 
Thanks for the code sample. I will give it a try and check out the windows.h header. I take it that FindFirstFile() is part of the windows.h header?

Hugh
 
is a part of WinAPI and the prototype is declared in winuser.h. To use it you should include windows.h

Ion Filipski
1c.bmp
 
Hi Ion,
Thanks for the reply. I can see that as I learn C++ I will need to learn more about the WinAPI. I suppose Mac's have their own API.

Hugh
 
If you have Microsoft software on your MAC then you can use WinAPI

Ion Filipski
1c.bmp
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top