// module dir_testw.cpp
// Oeffnet ein Windows Verzeichnis, liest die Eintraege aus und zeigt sie an
// Copyright Dr.E.Huckert 1-2014

// Wichtig: nicht UNIX getdirentries() verwenden - funktioniert nicht
// Unter Windows funktionieren auch LINUX Funktionen wie readdir(), 
//   opendir() etc. nicht!
// Digital Mars: Compile Symbol -DDMC als Compileroption setzen
// Kompilieren: dmc -mn -DDMC -Id:\dm\stlport\stlport dir_testw.cpp

#include <windows.h>
#ifdef DMC
#include <iostream.h>   // fuer Digital Mars
#else
#include <iostream>     // fuer Microsoft etc.
#endif
#include <string>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>

using namespace std;    // evtl. fuer Microsoft weg

// ------------------------------------------------------------------
// Traverse a directory and the embbeded directories
// Calls itself recursively!
void traverseDirectory(const char *directory)
{
  WIN32_FIND_DATA file;
  HANDLE hsearch;
  string dirFn = "";
  string fileAbsPath = "";
  //
  cout << "traverseDirectory(): directory=" <<
          directory << endl;
  dirFn = directory;
  dirFn = dirFn + "\\*";
  hsearch = ::FindFirstFile(dirFn.c_str(), &file);
  if (hsearch == INVALID_HANDLE_VALUE)
  {
    cout << "ERROR: invalid FindFirstFile argument=" << dirFn << endl;
    return;
  }
  //
  do
  {
    if (::strcmp(file.cFileName, "..") == 0)
      // don't look into the upward link
      continue;
    if (::strcmp(file.cFileName, ".") == 0)
      // ignore the actual directory
      continue;
    fileAbsPath = directory;
    fileAbsPath = fileAbsPath + "\\";
    fileAbsPath = fileAbsPath + file.cFileName;
    if (file.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
    {
       // this is a directory: recursive call
      cout << "--- directory=" << fileAbsPath << endl;
      traverseDirectory(fileAbsPath.c_str());
    }
    else
    {
      // this is a normal file
      cout << "file name=" << fileAbsPath << endl;
    }
   } while (::FindNextFile(hsearch, &file));
  //
  ::FindClose(hsearch); 
}   // end traverseDirectory()

// ----------------------------------------------------
int main(int argc, char *argv[])
{
  int n;
  if (argc < 2)
  {
    cout << "usage: dir_testw directory" << endl;
    ::exit(0);
  }
  traverseDirectory(argv[1]);
  //
  return 0;
}   // end  main()

